blob: def306da70d81b94ca509b8b26d2d03d84506951 [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;
Paul Crowley3d98f5d2020-02-07 11:49:09 -080077using android::vold::KeyBuffer;
David Andersonb9224732019-05-13 13:02:54 -070078using namespace android::dm;
Paul Crowleycfe39722018-10-30 15:59:24 -070079using namespace std::chrono_literals;
80
Paul Crowley73be12d2020-02-03 12:22:03 -080081/* The current cryptfs version */
82#define CURRENT_MAJOR_VERSION 1
83#define CURRENT_MINOR_VERSION 3
84
85#define CRYPT_FOOTER_TO_PERSIST_OFFSET 0x1000
86#define CRYPT_PERSIST_DATA_SIZE 0x1000
87
88#define MAX_CRYPTO_TYPE_NAME_LEN 64
89
90#define MAX_KEY_LEN 48
91#define SALT_LEN 16
92#define SCRYPT_LEN 32
93
94/* definitions of flags in the structure below */
95#define CRYPT_MNT_KEY_UNENCRYPTED 0x1 /* The key for the partition is not encrypted. */
96#define CRYPT_ENCRYPTION_IN_PROGRESS \
97 0x2 /* Encryption partially completed, \
98 encrypted_upto valid*/
99#define CRYPT_INCONSISTENT_STATE \
100 0x4 /* Set when starting encryption, clear when \
101 exit cleanly, either through success or \
102 correctly marked partial encryption */
103#define CRYPT_DATA_CORRUPT \
104 0x8 /* Set when encryption is fine, but the \
105 underlying volume is corrupt */
106#define CRYPT_FORCE_ENCRYPTION \
107 0x10 /* Set when it is time to encrypt this \
108 volume on boot. Everything in this \
109 structure is set up correctly as \
110 though device is encrypted except \
111 that the master key is encrypted with the \
112 default password. */
113#define CRYPT_FORCE_COMPLETE \
114 0x20 /* Set when the above encryption cycle is \
115 complete. On next cryptkeeper entry, match \
116 the password. If it matches fix the master \
117 key and remove this flag. */
118
119/* Allowed values for type in the structure below */
120#define CRYPT_TYPE_PASSWORD \
121 0 /* master_key is encrypted with a password \
122 * Must be zero to be compatible with pre-L \
123 * devices where type is always password.*/
124#define CRYPT_TYPE_DEFAULT \
125 1 /* master_key is encrypted with default \
126 * password */
127#define CRYPT_TYPE_PATTERN 2 /* master_key is encrypted with a pattern */
128#define CRYPT_TYPE_PIN 3 /* master_key is encrypted with a pin */
129#define CRYPT_TYPE_MAX_TYPE 3 /* type cannot be larger than this value */
130
131#define CRYPT_MNT_MAGIC 0xD0B5B1C4
132#define PERSIST_DATA_MAGIC 0xE950CD44
133
134/* Key Derivation Function algorithms */
135#define KDF_PBKDF2 1
136#define KDF_SCRYPT 2
137/* Algorithms 3 & 4 deprecated before shipping outside of google, so removed */
138#define KDF_SCRYPT_KEYMASTER 5
139
140/* Maximum allowed keymaster blob size. */
141#define KEYMASTER_BLOB_SIZE 2048
142
143/* __le32 and __le16 defined in system/extras/ext4_utils/ext4_utils.h */
144#define __le8 unsigned char
145
146#if !defined(SHA256_DIGEST_LENGTH)
147#define SHA256_DIGEST_LENGTH 32
148#endif
149
150/* This structure starts 16,384 bytes before the end of a hardware
151 * partition that is encrypted, or in a separate partition. It's location
152 * is specified by a property set in init.<device>.rc.
153 * The structure allocates 48 bytes for a key, but the real key size is
154 * specified in the struct. Currently, the code is hardcoded to use 128
155 * bit keys.
156 * The fields after salt are only valid in rev 1.1 and later stuctures.
157 * Obviously, the filesystem does not include the last 16 kbytes
158 * of the partition if the crypt_mnt_ftr lives at the end of the
159 * partition.
160 */
161
162struct crypt_mnt_ftr {
163 __le32 magic; /* See above */
164 __le16 major_version;
165 __le16 minor_version;
166 __le32 ftr_size; /* in bytes, not including key following */
167 __le32 flags; /* See above */
168 __le32 keysize; /* in bytes */
169 __le32 crypt_type; /* how master_key is encrypted. Must be a
170 * CRYPT_TYPE_XXX value */
171 __le64 fs_size; /* Size of the encrypted fs, in 512 byte sectors */
172 __le32 failed_decrypt_count; /* count of # of failed attempts to decrypt and
173 mount, set to 0 on successful mount */
174 unsigned char crypto_type_name[MAX_CRYPTO_TYPE_NAME_LEN]; /* The type of encryption
175 needed to decrypt this
176 partition, null terminated */
177 __le32 spare2; /* ignored */
178 unsigned char master_key[MAX_KEY_LEN]; /* The encrypted key for decrypting the filesystem */
179 unsigned char salt[SALT_LEN]; /* The salt used for this encryption */
180 __le64 persist_data_offset[2]; /* Absolute offset to both copies of crypt_persist_data
181 * on device with that info, either the footer of the
182 * real_blkdevice or the metadata partition. */
183
184 __le32 persist_data_size; /* The number of bytes allocated to each copy of the
185 * persistent data table*/
186
187 __le8 kdf_type; /* The key derivation function used. */
188
189 /* scrypt parameters. See www.tarsnap.com/scrypt/scrypt.pdf */
190 __le8 N_factor; /* (1 << N) */
191 __le8 r_factor; /* (1 << r) */
192 __le8 p_factor; /* (1 << p) */
193 __le64 encrypted_upto; /* If we are in state CRYPT_ENCRYPTION_IN_PROGRESS and
194 we have to stop (e.g. power low) this is the last
195 encrypted 512 byte sector.*/
196 __le8 hash_first_block[SHA256_DIGEST_LENGTH]; /* When CRYPT_ENCRYPTION_IN_PROGRESS
197 set, hash of first block, used
198 to validate before continuing*/
199
200 /* key_master key, used to sign the derived key which is then used to generate
201 * the intermediate key
202 * This key should be used for no other purposes! We use this key to sign unpadded
203 * data, which is acceptable but only if the key is not reused elsewhere. */
204 __le8 keymaster_blob[KEYMASTER_BLOB_SIZE];
205 __le32 keymaster_blob_size;
206
207 /* Store scrypt of salted intermediate key. When decryption fails, we can
208 check if this matches, and if it does, we know that the problem is with the
209 drive, and there is no point in asking the user for more passwords.
210
211 Note that if any part of this structure is corrupt, this will not match and
212 we will continue to believe the user entered the wrong password. In that
213 case the only solution is for the user to enter a password enough times to
214 force a wipe.
215
216 Note also that there is no need to worry about migration. If this data is
217 wrong, we simply won't recognise a right password, and will continue to
218 prompt. On the first password change, this value will be populated and
219 then we will be OK.
220 */
221 unsigned char scrypted_intermediate_key[SCRYPT_LEN];
222
223 /* sha of this structure with this element set to zero
224 Used when encrypting on reboot to validate structure before doing something
225 fatal
226 */
227 unsigned char sha256[SHA256_DIGEST_LENGTH];
228};
229
230/* Persistant data that should be available before decryption.
231 * Things like airplane mode, locale and timezone are kept
232 * here and can be retrieved by the CryptKeeper UI to properly
233 * configure the phone before asking for the password
234 * This is only valid if the major and minor version above
235 * is set to 1.1 or higher.
236 *
237 * This is a 4K structure. There are 2 copies, and the code alternates
238 * writing one and then clearing the previous one. The reading
239 * code reads the first valid copy it finds, based on the magic number.
240 * The absolute offset to the first of the two copies is kept in rev 1.1
241 * and higher crypt_mnt_ftr structures.
242 */
243struct crypt_persist_entry {
244 char key[PROPERTY_KEY_MAX];
245 char val[PROPERTY_VALUE_MAX];
246};
247
248/* Should be exactly 4K in size */
249struct crypt_persist_data {
250 __le32 persist_magic;
251 __le32 persist_valid_entries;
252 __le32 persist_spare[30];
253 struct crypt_persist_entry persist_entry[0];
254};
255
256static int wait_and_unmount(const char* mountpoint, bool kill);
257
258typedef int (*kdf_func)(const char* passwd, const unsigned char* salt, unsigned char* ikey,
259 void* params);
260
Mark Salyzyn5eecc442014-02-12 14:16:14 -0800261#define UNUSED __attribute__((unused))
262
Jason parks70a4b3f2011-01-28 10:10:47 -0600263#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800264
265constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
266constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -0700267constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -0800268
269// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -0700270static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -0600271
Paul Crowley14c8c072018-09-18 13:30:21 -0700272#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -0700273
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700274#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -0800275
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800276#define CRYPTO_BLOCK_DEVICE "userdata"
277
278#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
279
Ken Sumrall29d8da82011-05-18 17:20:07 -0700280#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700281#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700282
Ken Sumralle919efe2012-09-29 17:07:41 -0700283#define TABLE_LOAD_RETRIES 10
284
Shawn Willden47ba10d2014-09-03 17:07:06 -0600285#define RSA_KEY_SIZE 2048
286#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
287#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600288#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700289
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700290#define RETRY_MOUNT_ATTEMPTS 10
291#define RETRY_MOUNT_DELAY_SECONDS 1
292
Paul Crowley5afbc622017-11-27 09:42:17 -0800293#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
294
Paul Crowley73473332017-11-21 15:43:51 -0800295static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
296
Greg Kaiser59ad0182018-02-16 13:01:36 -0800297static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700298static char* saved_mount_point;
299static int master_key_saved = 0;
300static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800301
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700302/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700303static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000304 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700305}
306
307/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700308static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800309 if (ftr->keymaster_blob_size) {
310 SLOGI("Already have key");
311 return 0;
312 }
313
Paul Crowley14c8c072018-09-18 13:30:21 -0700314 int rc = keymaster_create_key_for_cryptfs_scrypt(
315 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
316 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000317 if (rc) {
318 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800319 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000320 ftr->keymaster_blob_size = 0;
321 }
322 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700323 return -1;
324 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000325 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700326}
327
Shawn Willdene17a9c42014-09-08 13:04:08 -0600328/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700329static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
330 const size_t object_size, unsigned char** signature,
331 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600332 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600333 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600334 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600335
Shawn Willdene17a9c42014-09-08 13:04:08 -0600336 // To sign a message with RSA, the message must satisfy two
337 // constraints:
338 //
339 // 1. The message, when interpreted as a big-endian numeric value, must
340 // be strictly less than the public modulus of the RSA key. Note
341 // that because the most significant bit of the public modulus is
342 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
343 // key), an n-bit message with most significant bit 0 always
344 // satisfies this requirement.
345 //
346 // 2. The message must have the same length in bits as the public
347 // modulus of the RSA key. This requirement isn't mathematically
348 // necessary, but is necessary to ensure consistency in
349 // implementations.
350 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600351 case KDF_SCRYPT_KEYMASTER:
352 // This ensures the most significant byte of the signed message
353 // is zero. We could have zero-padded to the left instead, but
354 // this approach is slightly more robust against changes in
355 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600356 // so) because we really should be using a proper deterministic
357 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800358 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600359 SLOGI("Signing safely-padded object");
360 break;
361 default:
362 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000363 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600364 }
Paul Crowley73473332017-11-21 15:43:51 -0800365 for (;;) {
366 auto result = keymaster_sign_object_for_cryptfs_scrypt(
367 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
368 to_sign_size, signature, signature_size);
369 switch (result) {
370 case KeymasterSignResult::ok:
371 return 0;
372 case KeymasterSignResult::upgrade:
373 break;
374 default:
375 return -1;
376 }
377 SLOGD("Upgrading key");
378 if (keymaster_upgrade_key_for_cryptfs_scrypt(
379 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
380 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
381 &ftr->keymaster_blob_size) != 0) {
382 SLOGE("Failed to upgrade key");
383 return -1;
384 }
385 if (put_crypt_ftr_and_key(ftr) != 0) {
386 SLOGE("Failed to write upgraded key to disk");
387 }
388 SLOGD("Key upgraded successfully");
389 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600390}
391
Paul Lawrence399317e2014-03-10 13:20:50 -0700392/* Store password when userdata is successfully decrypted and mounted.
393 * Cleared by cryptfs_clear_password
394 *
395 * To avoid a double prompt at boot, we need to store the CryptKeeper
396 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
397 * Since the entire framework is torn down and rebuilt after encryption,
398 * we have to use a daemon or similar to store the password. Since vold
399 * is secured against IPC except from system processes, it seems a reasonable
400 * place to store this.
401 *
402 * password should be cleared once it has been used.
403 *
404 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800405 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700406static char* password = 0;
407static int password_expiry_time = 0;
408static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800409
Paul Crowley14c8c072018-09-18 13:30:21 -0700410enum class RebootType { reboot, recovery, shutdown };
411static void cryptfs_reboot(RebootType rt) {
412 switch (rt) {
413 case RebootType::reboot:
414 property_set(ANDROID_RB_PROPERTY, "reboot");
415 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800416
Paul Crowley14c8c072018-09-18 13:30:21 -0700417 case RebootType::recovery:
418 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
419 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800420
Paul Crowley14c8c072018-09-18 13:30:21 -0700421 case RebootType::shutdown:
422 property_set(ANDROID_RB_PROPERTY, "shutdown");
423 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700424 }
Paul Lawrence87999172014-02-20 12:21:31 -0800425
Ken Sumralladfba362013-06-04 16:37:52 -0700426 sleep(20);
427
428 /* Shouldn't get here, reboot should happen before sleep times out */
429 return;
430}
431
Greg Kaiser38723f22018-02-16 13:35:35 -0800432namespace {
433
434struct CryptoType;
435
436// Use to get the CryptoType in use on this device.
Paul Crowley14c8c072018-09-18 13:30:21 -0700437const CryptoType& get_crypto_type();
Greg Kaiser38723f22018-02-16 13:35:35 -0800438
439struct CryptoType {
440 // We should only be constructing CryptoTypes as part of
441 // supported_crypto_types[]. We do it via this pseudo-builder pattern,
442 // which isn't pure or fully protected as a concession to being able to
443 // do it all at compile time. Add new CryptoTypes in
444 // supported_crypto_types[] below.
445 constexpr CryptoType() : CryptoType(nullptr, nullptr, 0xFFFFFFFF) {}
446 constexpr CryptoType set_keysize(uint32_t size) const {
447 return CryptoType(this->property_name, this->crypto_name, size);
448 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700449 constexpr CryptoType set_property_name(const char* property) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800450 return CryptoType(property, this->crypto_name, this->keysize);
451 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700452 constexpr CryptoType set_crypto_name(const char* crypto) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800453 return CryptoType(this->property_name, crypto, this->keysize);
454 }
455
Paul Crowley14c8c072018-09-18 13:30:21 -0700456 constexpr const char* get_property_name() const { return property_name; }
457 constexpr const char* get_crypto_name() const { return crypto_name; }
Greg Kaiser38723f22018-02-16 13:35:35 -0800458 constexpr uint32_t get_keysize() const { return keysize; }
459
Paul Crowley14c8c072018-09-18 13:30:21 -0700460 private:
461 const char* property_name;
462 const char* crypto_name;
Greg Kaiser38723f22018-02-16 13:35:35 -0800463 uint32_t keysize;
464
Paul Crowley14c8c072018-09-18 13:30:21 -0700465 constexpr CryptoType(const char* property, const char* crypto, uint32_t ksize)
Greg Kaiser38723f22018-02-16 13:35:35 -0800466 : property_name(property), crypto_name(crypto), keysize(ksize) {}
Paul Crowley14c8c072018-09-18 13:30:21 -0700467 friend const CryptoType& get_crypto_type();
468 static const CryptoType& get_device_crypto_algorithm();
Greg Kaiser38723f22018-02-16 13:35:35 -0800469};
470
471// We only want to parse this read-only property once. But we need to wait
472// until the system is initialized before we can read it. So we use a static
473// scoped within this function to get it only once.
Paul Crowley14c8c072018-09-18 13:30:21 -0700474const CryptoType& get_crypto_type() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800475 static CryptoType crypto_type = CryptoType::get_device_crypto_algorithm();
476 return crypto_type;
477}
478
479constexpr CryptoType default_crypto_type = CryptoType()
Paul Crowley14c8c072018-09-18 13:30:21 -0700480 .set_property_name("AES-128-CBC")
481 .set_crypto_name("aes-cbc-essiv:sha256")
482 .set_keysize(16);
Greg Kaiser38723f22018-02-16 13:35:35 -0800483
484constexpr CryptoType supported_crypto_types[] = {
485 default_crypto_type,
Greg Kaiser8cb4c9f2018-12-03 11:23:19 -0800486 CryptoType()
487 .set_property_name("adiantum")
488 .set_crypto_name("xchacha12,aes-adiantum-plain64")
489 .set_keysize(32),
Greg Kaiser38723f22018-02-16 13:35:35 -0800490 // Add new CryptoTypes here. Order is not important.
491};
492
Greg Kaiser38723f22018-02-16 13:35:35 -0800493// ---------- START COMPILE-TIME SANITY CHECK BLOCK -------------------------
494// We confirm all supported_crypto_types have a small enough keysize and
495// had both set_property_name() and set_crypto_name() called.
496
497template <typename T, size_t N>
Paul Crowley14c8c072018-09-18 13:30:21 -0700498constexpr size_t array_length(T (&)[N]) {
499 return N;
500}
Greg Kaiser38723f22018-02-16 13:35:35 -0800501
502constexpr bool indexOutOfBoundsForCryptoTypes(size_t index) {
503 return (index >= array_length(supported_crypto_types));
504}
505
Paul Crowley14c8c072018-09-18 13:30:21 -0700506constexpr bool isValidCryptoType(const CryptoType& crypto_type) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800507 return ((crypto_type.get_property_name() != nullptr) &&
508 (crypto_type.get_crypto_name() != nullptr) &&
509 (crypto_type.get_keysize() <= MAX_KEY_LEN));
510}
511
512// Note in C++11 that constexpr functions can only have a single line.
513// So our code is a bit convoluted (using recursion instead of a loop),
514// but it's asserting at compile time that all of our key lengths are valid.
515constexpr bool validateSupportedCryptoTypes(size_t index) {
516 return indexOutOfBoundsForCryptoTypes(index) ||
Paul Crowley14c8c072018-09-18 13:30:21 -0700517 (isValidCryptoType(supported_crypto_types[index]) &&
518 validateSupportedCryptoTypes(index + 1));
Greg Kaiser38723f22018-02-16 13:35:35 -0800519}
520
521static_assert(validateSupportedCryptoTypes(0),
522 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
523 "incompletely constructed.");
524// ---------- END COMPILE-TIME SANITY CHECK BLOCK -------------------------
525
Greg Kaiser38723f22018-02-16 13:35:35 -0800526// Don't call this directly, use get_crypto_type(), which caches this result.
Paul Crowley14c8c072018-09-18 13:30:21 -0700527const CryptoType& CryptoType::get_device_crypto_algorithm() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800528 constexpr char CRYPT_ALGO_PROP[] = "ro.crypto.fde_algorithm";
529 char paramstr[PROPERTY_VALUE_MAX];
530
Paul Crowley14c8c072018-09-18 13:30:21 -0700531 property_get(CRYPT_ALGO_PROP, paramstr, default_crypto_type.get_property_name());
532 for (auto const& ctype : supported_crypto_types) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800533 if (strcmp(paramstr, ctype.get_property_name()) == 0) {
534 return ctype;
535 }
536 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700537 ALOGE("Invalid name (%s) for %s. Defaulting to %s\n", paramstr, CRYPT_ALGO_PROP,
538 default_crypto_type.get_property_name());
Greg Kaiser38723f22018-02-16 13:35:35 -0800539 return default_crypto_type;
540}
541
542} // namespace
543
Kenny Rootc4c70f12013-06-14 12:11:38 -0700544/**
545 * Gets the default device scrypt parameters for key derivation time tuning.
546 * The parameters should lead to about one second derivation time for the
547 * given device.
548 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700549static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700550 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000551 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700552
Paul Crowley63c18d32016-02-10 14:02:47 +0000553 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
554 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
555 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
556 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700557 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000558 ftr->N_factor = Nf;
559 ftr->r_factor = rf;
560 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700561}
562
Greg Kaiser57f9af62018-02-16 13:13:58 -0800563uint32_t cryptfs_get_keysize() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800564 return get_crypto_type().get_keysize();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800565}
566
Paul Crowley14c8c072018-09-18 13:30:21 -0700567const char* cryptfs_get_crypto_name() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800568 return get_crypto_type().get_crypto_name();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800569}
570
Tom Cherry4c5bde22019-01-29 14:34:01 -0800571static uint64_t get_fs_size(const char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800572 int fd, block_size;
573 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200574 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800575
Paul Crowley14c8c072018-09-18 13:30:21 -0700576 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800577 SLOGE("Cannot open device to get filesystem size ");
578 return 0;
579 }
580
581 if (lseek64(fd, 1024, SEEK_SET) < 0) {
582 SLOGE("Cannot seek to superblock");
583 return 0;
584 }
585
586 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
587 SLOGE("Cannot read superblock");
588 return 0;
589 }
590
591 close(fd);
592
Daniel Rosenberge82df162014-08-15 22:19:23 +0000593 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
594 SLOGE("Not a valid ext4 superblock");
595 return 0;
596 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800597 block_size = 1024 << sb.s_log_block_size;
598 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200599 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800600
601 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200602 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800603}
604
Tom Cherry4c5bde22019-01-29 14:34:01 -0800605static void get_crypt_info(std::string* key_loc, std::string* real_blk_device) {
606 for (const auto& entry : fstab_default) {
607 if (!entry.fs_mgr_flags.vold_managed &&
608 (entry.fs_mgr_flags.crypt || entry.fs_mgr_flags.force_crypt ||
609 entry.fs_mgr_flags.force_fde_or_fbe || entry.fs_mgr_flags.file_encryption)) {
610 if (key_loc != nullptr) {
611 *key_loc = entry.key_loc;
612 }
613 if (real_blk_device != nullptr) {
614 *real_blk_device = entry.blk_device;
615 }
616 return;
617 }
618 }
619}
620
Paul Crowley14c8c072018-09-18 13:30:21 -0700621static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
622 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200623 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700624 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700625 char key_loc[PROPERTY_VALUE_MAX];
626 char real_blkdev[PROPERTY_VALUE_MAX];
627 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700628
Paul Crowley14c8c072018-09-18 13:30:21 -0700629 if (!cached_data) {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800630 std::string key_loc;
631 std::string real_blkdev;
632 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700633
Tom Cherry4c5bde22019-01-29 14:34:01 -0800634 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200635 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700636 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
637 * encryption info footer and key, and plenty of bytes to spare for future
638 * growth.
639 */
Tom Cherry4c5bde22019-01-29 14:34:01 -0800640 strlcpy(cached_metadata_fname, real_blkdev.c_str(), sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200641 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700642 cached_data = 1;
643 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800644 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -0700645 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700646 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800647 strlcpy(cached_metadata_fname, key_loc.c_str(), sizeof(cached_metadata_fname));
Paul Crowley14c8c072018-09-18 13:30:21 -0700648 cached_off = 0;
649 cached_data = 1;
650 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700651 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700652
Paul Crowley14c8c072018-09-18 13:30:21 -0700653 if (cached_data) {
654 if (metadata_fname) {
655 *metadata_fname = cached_metadata_fname;
656 }
657 if (off) {
658 *off = cached_off;
659 }
660 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700661 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700662
Paul Crowley14c8c072018-09-18 13:30:21 -0700663 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700664}
665
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800666/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700667static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800668 SHA256_CTX c;
669 SHA256_Init(&c);
670 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
671 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
672 SHA256_Final(crypt_ftr->sha256, &c);
673}
674
Ken Sumralle8744072011-01-18 22:01:55 -0800675/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800676 * update the failed mount count but not change the key.
677 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700678static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
679 int fd;
680 unsigned int cnt;
681 /* starting_off is set to the SEEK_SET offset
682 * where the crypto structure starts
683 */
684 off64_t starting_off;
685 int rc = -1;
686 char* fname = NULL;
687 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800688
Paul Crowley14c8c072018-09-18 13:30:21 -0700689 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800690
Paul Crowley14c8c072018-09-18 13:30:21 -0700691 if (get_crypt_ftr_info(&fname, &starting_off)) {
692 SLOGE("Unable to get crypt_ftr_info\n");
693 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800694 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700695 if (fname[0] != '/') {
696 SLOGE("Unexpected value for crypto key location\n");
697 return -1;
698 }
699 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
700 SLOGE("Cannot open footer file %s for put\n", fname);
701 return -1;
702 }
Ken Sumralle8744072011-01-18 22:01:55 -0800703
Paul Crowley14c8c072018-09-18 13:30:21 -0700704 /* Seek to the start of the crypt footer */
705 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
706 SLOGE("Cannot seek to real block device footer\n");
707 goto errout;
708 }
709
710 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
711 SLOGE("Cannot write real block device footer\n");
712 goto errout;
713 }
714
715 fstat(fd, &statbuf);
716 /* If the keys are kept on a raw block device, do not try to truncate it. */
717 if (S_ISREG(statbuf.st_mode)) {
718 if (ftruncate(fd, 0x4000)) {
719 SLOGE("Cannot set footer file size\n");
720 goto errout;
721 }
722 }
723
724 /* Success! */
725 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800726
727errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700728 close(fd);
729 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800730}
731
Paul Crowley14c8c072018-09-18 13:30:21 -0700732static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800733 struct crypt_mnt_ftr copy;
734 memcpy(&copy, crypt_ftr, sizeof(copy));
735 set_ftr_sha(&copy);
736 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
737}
738
Paul Crowley14c8c072018-09-18 13:30:21 -0700739static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700740 return TEMP_FAILURE_RETRY(read(fd, buff, len));
741}
742
Paul Crowley14c8c072018-09-18 13:30:21 -0700743static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700744 return TEMP_FAILURE_RETRY(write(fd, buff, len));
745}
746
Paul Crowley14c8c072018-09-18 13:30:21 -0700747static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700748 memset(pdata, 0, len);
749 pdata->persist_magic = PERSIST_DATA_MAGIC;
750 pdata->persist_valid_entries = 0;
751}
752
753/* A routine to update the passed in crypt_ftr to the lastest version.
754 * fd is open read/write on the device that holds the crypto footer and persistent
755 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
756 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
757 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700758static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700759 int orig_major = crypt_ftr->major_version;
760 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700761
Kenny Root7434b312013-06-14 11:29:53 -0700762 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700763 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700764 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700765
Kenny Rootc4c70f12013-06-14 12:11:38 -0700766 SLOGW("upgrading crypto footer to 1.1");
767
Paul Crowley14c8c072018-09-18 13:30:21 -0700768 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700769 if (pdata == NULL) {
770 SLOGE("Cannot allocate persisent data\n");
771 return;
772 }
773 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
774
775 /* Need to initialize the persistent data area */
776 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
777 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100778 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700779 return;
780 }
781 /* Write all zeros to the first copy, making it invalid */
782 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
783
784 /* Write a valid but empty structure to the second copy */
785 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
786 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
787
788 /* Update the footer */
789 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
790 crypt_ftr->persist_data_offset[0] = pdata_offset;
791 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
792 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100793 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700794 }
795
Paul Lawrencef4faa572014-01-29 13:31:03 -0800796 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700797 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800798 /* But keep the old kdf_type.
799 * It will get updated later to KDF_SCRYPT after the password has been verified.
800 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700801 crypt_ftr->kdf_type = KDF_PBKDF2;
802 get_device_scrypt_params(crypt_ftr);
803 crypt_ftr->minor_version = 2;
804 }
805
Paul Lawrencef4faa572014-01-29 13:31:03 -0800806 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
807 SLOGW("upgrading crypto footer to 1.3");
808 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
809 crypt_ftr->minor_version = 3;
810 }
811
Kenny Root7434b312013-06-14 11:29:53 -0700812 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
813 if (lseek64(fd, offset, SEEK_SET) == -1) {
814 SLOGE("Cannot seek to crypt footer\n");
815 return;
816 }
817 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700818 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700819}
820
Paul Crowley14c8c072018-09-18 13:30:21 -0700821static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
822 int fd;
823 unsigned int cnt;
824 off64_t starting_off;
825 int rc = -1;
826 char* fname = NULL;
827 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700828
Paul Crowley14c8c072018-09-18 13:30:21 -0700829 if (get_crypt_ftr_info(&fname, &starting_off)) {
830 SLOGE("Unable to get crypt_ftr_info\n");
831 return -1;
832 }
833 if (fname[0] != '/') {
834 SLOGE("Unexpected value for crypto key location\n");
835 return -1;
836 }
837 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
838 SLOGE("Cannot open footer file %s for get\n", fname);
839 return -1;
840 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800841
Paul Crowley14c8c072018-09-18 13:30:21 -0700842 /* Make sure it's 16 Kbytes in length */
843 fstat(fd, &statbuf);
844 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
845 SLOGE("footer file %s is not the expected size!\n", fname);
846 goto errout;
847 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700848
Paul Crowley14c8c072018-09-18 13:30:21 -0700849 /* Seek to the start of the crypt footer */
850 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
851 SLOGE("Cannot seek to real block device footer\n");
852 goto errout;
853 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700854
Paul Crowley14c8c072018-09-18 13:30:21 -0700855 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
856 SLOGE("Cannot read real block device footer\n");
857 goto errout;
858 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800859
Paul Crowley14c8c072018-09-18 13:30:21 -0700860 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
861 SLOGE("Bad magic for real block device %s\n", fname);
862 goto errout;
863 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800864
Paul Crowley14c8c072018-09-18 13:30:21 -0700865 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
866 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
867 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
868 goto errout;
869 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800870
Paul Crowley14c8c072018-09-18 13:30:21 -0700871 // We risk buffer overflows with oversized keys, so we just reject them.
872 // 0-sized keys are problematic (essentially by-passing encryption), and
873 // AES-CBC key wrapping only works for multiples of 16 bytes.
874 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
875 (crypt_ftr->keysize > MAX_KEY_LEN)) {
876 SLOGE(
877 "Invalid keysize (%u) for block device %s; Must be non-zero, "
878 "divisible by 16, and <= %d\n",
879 crypt_ftr->keysize, fname, MAX_KEY_LEN);
880 goto errout;
881 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800882
Paul Crowley14c8c072018-09-18 13:30:21 -0700883 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
884 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
885 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
886 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800887
Paul Crowley14c8c072018-09-18 13:30:21 -0700888 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
889 * copy on disk before returning.
890 */
891 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
892 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
893 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800894
Paul Crowley14c8c072018-09-18 13:30:21 -0700895 /* Success! */
896 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800897
898errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700899 close(fd);
900 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800901}
902
Paul Crowley14c8c072018-09-18 13:30:21 -0700903static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700904 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
905 crypt_ftr->persist_data_offset[1]) {
906 SLOGE("Crypt_ftr persist data regions overlap");
907 return -1;
908 }
909
910 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
911 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
912 return -1;
913 }
914
915 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700916 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700917 CRYPT_FOOTER_OFFSET) {
918 SLOGE("Persistent data extends past crypto footer");
919 return -1;
920 }
921
922 return 0;
923}
924
Paul Crowley14c8c072018-09-18 13:30:21 -0700925static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700926 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700927 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700928 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700929 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700930 int found = 0;
931 int fd;
932 int ret;
933 int i;
934
935 if (persist_data) {
936 /* Nothing to do, we've already loaded or initialized it */
937 return 0;
938 }
939
Ken Sumrall160b4d62013-04-22 12:15:39 -0700940 /* If not encrypted, just allocate an empty table and initialize it */
941 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700942 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800943 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700944 if (pdata) {
945 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
946 persist_data = pdata;
947 return 0;
948 }
949 return -1;
950 }
951
Paul Crowley14c8c072018-09-18 13:30:21 -0700952 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700953 return -1;
954 }
955
Paul Crowley14c8c072018-09-18 13:30:21 -0700956 if ((crypt_ftr.major_version < 1) ||
957 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700958 SLOGE("Crypt_ftr version doesn't support persistent data");
959 return -1;
960 }
961
962 if (get_crypt_ftr_info(&fname, NULL)) {
963 return -1;
964 }
965
966 ret = validate_persistent_data_storage(&crypt_ftr);
967 if (ret) {
968 return -1;
969 }
970
Paul Crowley14c8c072018-09-18 13:30:21 -0700971 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700972 if (fd < 0) {
973 SLOGE("Cannot open %s metadata file", fname);
974 return -1;
975 }
976
Wei Wang4375f1b2017-02-24 17:43:01 -0800977 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800978 if (pdata == NULL) {
979 SLOGE("Cannot allocate memory for persistent data");
980 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700981 }
982
983 for (i = 0; i < 2; i++) {
984 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
985 SLOGE("Cannot seek to read persistent data on %s", fname);
986 goto err2;
987 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700988 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700989 SLOGE("Error reading persistent data on iteration %d", i);
990 goto err2;
991 }
992 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
993 found = 1;
994 break;
995 }
996 }
997
998 if (!found) {
999 SLOGI("Could not find valid persistent data, creating");
1000 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
1001 }
1002
1003 /* Success */
1004 persist_data = pdata;
1005 close(fd);
1006 return 0;
1007
1008err2:
1009 free(pdata);
1010
1011err:
1012 close(fd);
1013 return -1;
1014}
1015
Paul Crowley14c8c072018-09-18 13:30:21 -07001016static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001017 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07001018 struct crypt_persist_data* pdata;
1019 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001020 off64_t write_offset;
1021 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001022 int fd;
1023 int ret;
1024
1025 if (persist_data == NULL) {
1026 SLOGE("No persistent data to save");
1027 return -1;
1028 }
1029
Paul Crowley14c8c072018-09-18 13:30:21 -07001030 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001031 return -1;
1032 }
1033
Paul Crowley14c8c072018-09-18 13:30:21 -07001034 if ((crypt_ftr.major_version < 1) ||
1035 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001036 SLOGE("Crypt_ftr version doesn't support persistent data");
1037 return -1;
1038 }
1039
1040 ret = validate_persistent_data_storage(&crypt_ftr);
1041 if (ret) {
1042 return -1;
1043 }
1044
1045 if (get_crypt_ftr_info(&fname, NULL)) {
1046 return -1;
1047 }
1048
Paul Crowley14c8c072018-09-18 13:30:21 -07001049 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001050 if (fd < 0) {
1051 SLOGE("Cannot open %s metadata file", fname);
1052 return -1;
1053 }
1054
Wei Wang4375f1b2017-02-24 17:43:01 -08001055 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001056 if (pdata == NULL) {
1057 SLOGE("Cannot allocate persistant data");
1058 goto err;
1059 }
1060
1061 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
1062 SLOGE("Cannot seek to read persistent data on %s", fname);
1063 goto err2;
1064 }
1065
1066 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001067 SLOGE("Error reading persistent data before save");
1068 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001069 }
1070
1071 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
1072 /* The first copy is the curent valid copy, so write to
1073 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -07001074 write_offset = crypt_ftr.persist_data_offset[1];
1075 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001076 } else {
1077 /* The second copy must be the valid copy, so write to
1078 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -07001079 write_offset = crypt_ftr.persist_data_offset[0];
1080 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001081 }
1082
1083 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +01001084 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001085 SLOGE("Cannot seek to write persistent data");
1086 goto err2;
1087 }
1088 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -07001089 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +01001090 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001091 SLOGE("Cannot seek to erase previous persistent data");
1092 goto err2;
1093 }
1094 fsync(fd);
1095 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -07001096 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001097 SLOGE("Cannot write to erase previous persistent data");
1098 goto err2;
1099 }
1100 fsync(fd);
1101 } else {
1102 SLOGE("Cannot write to save persistent data");
1103 goto err2;
1104 }
1105
1106 /* Success */
1107 free(pdata);
1108 close(fd);
1109 return 0;
1110
1111err2:
1112 free(pdata);
1113err:
1114 close(fd);
1115 return -1;
1116}
1117
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001118/* Convert a binary key of specified length into an ascii hex string equivalent,
1119 * without the leading 0x and with null termination
1120 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001121static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
1122 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001123 unsigned int i, a;
1124 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001125
Paul Crowley14c8c072018-09-18 13:30:21 -07001126 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001127 /* For each byte, write out two ascii hex digits */
1128 nibble = (master_key[i] >> 4) & 0xf;
1129 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001130
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001131 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001132 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001133 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001134
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001135 /* Add the null termination */
1136 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001137}
1138
Eric Biggersed45ec32019-01-25 10:47:55 -08001139/*
1140 * If the ro.crypto.fde_sector_size system property is set, append the
1141 * parameters to make dm-crypt use the specified crypto sector size and round
1142 * the crypto device size down to a crypto sector boundary.
1143 */
David Andersonb9224732019-05-13 13:02:54 -07001144static int add_sector_size_param(DmTargetCrypt* target, struct crypt_mnt_ftr* ftr) {
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001145 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
Eric Biggersed45ec32019-01-25 10:47:55 -08001146 char value[PROPERTY_VALUE_MAX];
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001147
Eric Biggersed45ec32019-01-25 10:47:55 -08001148 if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
1149 unsigned int sector_size;
1150
1151 if (!ParseUint(value, &sector_size) || sector_size < 512 || sector_size > 4096 ||
1152 (sector_size & (sector_size - 1)) != 0) {
1153 SLOGE("Invalid value for %s: %s. Must be >= 512, <= 4096, and a power of 2\n",
1154 DM_CRYPT_SECTOR_SIZE, value);
1155 return -1;
1156 }
1157
David Andersonb9224732019-05-13 13:02:54 -07001158 target->SetSectorSize(sector_size);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001159
1160 // With this option, IVs will match the sector numbering, instead
1161 // of being hard-coded to being based on 512-byte sectors.
David Andersonb9224732019-05-13 13:02:54 -07001162 target->SetIvLargeSectors();
Eric Biggersed45ec32019-01-25 10:47:55 -08001163
1164 // Round the crypto device size down to a crypto sector boundary.
1165 ftr->fs_size &= ~((sector_size / 512) - 1);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001166 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001167 return 0;
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001168}
1169
Paul Crowley5afbc622017-11-27 09:42:17 -08001170static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
Paul Crowley81796e92020-02-07 11:27:49 -08001171 const char* real_blk_name, std::string* crypto_blk_name,
1172 const char* name, uint32_t flags) {
David Andersonb9224732019-05-13 13:02:54 -07001173 auto& dm = DeviceMapper::Instance();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001174
David Andersonb9224732019-05-13 13:02:54 -07001175 // We need two ASCII characters to represent each byte, and need space for
1176 // the '\0' terminator.
1177 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1178 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001179
David Andersonb9224732019-05-13 13:02:54 -07001180 auto target = std::make_unique<DmTargetCrypt>(0, crypt_ftr->fs_size,
1181 (const char*)crypt_ftr->crypto_type_name,
1182 master_key_ascii, 0, real_blk_name, 0);
1183 target->AllowDiscards();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001184
Paul Crowley5afbc622017-11-27 09:42:17 -08001185 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
David Andersonb9224732019-05-13 13:02:54 -07001186 target->AllowEncryptOverride();
Paul Crowley5afbc622017-11-27 09:42:17 -08001187 }
David Andersonb9224732019-05-13 13:02:54 -07001188 if (add_sector_size_param(target.get(), crypt_ftr)) {
Eric Biggersed45ec32019-01-25 10:47:55 -08001189 SLOGE("Error processing dm-crypt sector size param\n");
David Andersonb9224732019-05-13 13:02:54 -07001190 return -1;
Eric Biggersed45ec32019-01-25 10:47:55 -08001191 }
David Andersonb9224732019-05-13 13:02:54 -07001192
1193 DmTable table;
1194 table.AddTarget(std::move(target));
1195
1196 int load_count = 1;
1197 while (load_count < TABLE_LOAD_RETRIES) {
1198 if (dm.CreateDevice(name, table)) {
1199 break;
1200 }
1201 load_count++;
1202 }
1203
1204 if (load_count >= TABLE_LOAD_RETRIES) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001205 SLOGE("Cannot load dm-crypt mapping table.\n");
David Andersonb9224732019-05-13 13:02:54 -07001206 return -1;
1207 }
1208 if (load_count > 1) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001209 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1210 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001211
Paul Crowley81796e92020-02-07 11:27:49 -08001212 if (!dm.GetDmDevicePathByName(name, crypto_blk_name)) {
David Andersonb9224732019-05-13 13:02:54 -07001213 SLOGE("Cannot determine dm-crypt path for %s.\n", name);
1214 return -1;
Paul Crowley5afbc622017-11-27 09:42:17 -08001215 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001216
Paul Crowleycfe39722018-10-30 15:59:24 -07001217 /* Ensure the dm device has been created before returning. */
Paul Crowley81796e92020-02-07 11:27:49 -08001218 if (android::vold::WaitForFile(crypto_blk_name->c_str(), 1s) < 0) {
Paul Crowleycfe39722018-10-30 15:59:24 -07001219 // WaitForFile generates a suitable log message
David Andersonb9224732019-05-13 13:02:54 -07001220 return -1;
Paul Crowleycfe39722018-10-30 15:59:24 -07001221 }
David Andersonb9224732019-05-13 13:02:54 -07001222 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001223}
1224
David Andersonb9224732019-05-13 13:02:54 -07001225static int delete_crypto_blk_dev(const std::string& name) {
Martijn Coenen26ad7b32020-02-13 16:20:52 +01001226 bool ret;
David Andersonb9224732019-05-13 13:02:54 -07001227 auto& dm = DeviceMapper::Instance();
Martijn Coenen26ad7b32020-02-13 16:20:52 +01001228 // TODO(b/149396179) there appears to be a race somewhere in the system where trying
1229 // to delete the device fails with EBUSY; for now, work around this by retrying.
1230 int tries = 5;
1231 while (tries-- > 0) {
1232 ret = dm.DeleteDevice(name);
1233 if (ret || errno != EBUSY) {
1234 break;
1235 }
1236 SLOGW("DM_DEV Cannot remove dm-crypt device %s: %s, retrying...\n", name.c_str(),
1237 strerror(errno));
1238 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1239 }
1240 if (!ret) {
1241 SLOGE("DM_DEV Cannot remove dm-crypt device %s: %s\n", name.c_str(), strerror(errno));
David Andersonb9224732019-05-13 13:02:54 -07001242 return -1;
Paul Crowley14c8c072018-09-18 13:30:21 -07001243 }
David Andersonb9224732019-05-13 13:02:54 -07001244 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001245}
1246
Paul Crowley14c8c072018-09-18 13:30:21 -07001247static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1248 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001249 SLOGI("Using pbkdf2 for cryptfs KDF");
1250
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001251 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001252 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1253 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001254}
1255
Paul Crowley14c8c072018-09-18 13:30:21 -07001256static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001257 SLOGI("Using scrypt for cryptfs KDF");
1258
Paul Crowley14c8c072018-09-18 13:30:21 -07001259 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001260
1261 int N = 1 << ftr->N_factor;
1262 int r = 1 << ftr->r_factor;
1263 int p = 1 << ftr->p_factor;
1264
1265 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001266 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001267 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001268
Paul Crowley14c8c072018-09-18 13:30:21 -07001269 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001270}
1271
Paul Crowley14c8c072018-09-18 13:30:21 -07001272static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1273 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001274 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1275
1276 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001277 size_t signature_size;
1278 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001279 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001280
1281 int N = 1 << ftr->N_factor;
1282 int r = 1 << ftr->r_factor;
1283 int p = 1 << ftr->p_factor;
1284
Paul Crowley14c8c072018-09-18 13:30:21 -07001285 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001286 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001287
1288 if (rc) {
1289 SLOGE("scrypt failed");
1290 return -1;
1291 }
1292
Paul Crowley14c8c072018-09-18 13:30:21 -07001293 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001294 SLOGE("Signing failed");
1295 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001296 }
1297
Paul Crowley14c8c072018-09-18 13:30:21 -07001298 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1299 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001300 free(signature);
1301
1302 if (rc) {
1303 SLOGE("scrypt failed");
1304 return -1;
1305 }
1306
1307 return 0;
1308}
1309
Paul Crowley14c8c072018-09-18 13:30:21 -07001310static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1311 const unsigned char* decrypted_master_key,
1312 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr) {
1313 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001314 EVP_CIPHER_CTX e_ctx;
1315 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001316 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001317
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001318 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001319 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001320
1321 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001322 case KDF_SCRYPT_KEYMASTER:
1323 if (keymaster_create_key(crypt_ftr)) {
1324 SLOGE("keymaster_create_key failed");
1325 return -1;
1326 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001327
Paul Crowley14c8c072018-09-18 13:30:21 -07001328 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1329 SLOGE("scrypt failed");
1330 return -1;
1331 }
1332 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001333
Paul Crowley14c8c072018-09-18 13:30:21 -07001334 case KDF_SCRYPT:
1335 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1336 SLOGE("scrypt failed");
1337 return -1;
1338 }
1339 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001340
Paul Crowley14c8c072018-09-18 13:30:21 -07001341 default:
1342 SLOGE("Invalid kdf_type");
1343 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001344 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001345
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001346 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001347 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001348 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1349 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001350 SLOGE("EVP_EncryptInit failed\n");
1351 return -1;
1352 }
1353 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001354
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001355 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001356 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1357 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001358 SLOGE("EVP_EncryptUpdate failed\n");
1359 return -1;
1360 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001361 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001362 SLOGE("EVP_EncryptFinal failed\n");
1363 return -1;
1364 }
1365
Greg Kaiser59ad0182018-02-16 13:01:36 -08001366 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001367 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1368 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001369 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001370
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001371 /* Store the scrypt of the intermediate key, so we can validate if it's a
1372 password error or mount error when things go wrong.
1373 Note there's no need to check for errors, since if this is incorrect, we
1374 simply won't wipe userdata, which is the correct default behavior
1375 */
1376 int N = 1 << crypt_ftr->N_factor;
1377 int r = 1 << crypt_ftr->r_factor;
1378 int p = 1 << crypt_ftr->p_factor;
1379
Paul Crowley14c8c072018-09-18 13:30:21 -07001380 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1381 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001382 sizeof(crypt_ftr->scrypted_intermediate_key));
1383
1384 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001385 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001386 }
1387
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001388 EVP_CIPHER_CTX_cleanup(&e_ctx);
1389
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001390 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001391}
1392
Paul Crowley14c8c072018-09-18 13:30:21 -07001393static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1394 const unsigned char* encrypted_master_key, size_t keysize,
1395 unsigned char* decrypted_master_key, kdf_func kdf,
1396 void* kdf_params, unsigned char** intermediate_key,
1397 size_t* intermediate_key_size) {
1398 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1399 EVP_CIPHER_CTX d_ctx;
1400 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001401
Paul Crowley14c8c072018-09-18 13:30:21 -07001402 /* Turn the password into an intermediate key and IV that can decrypt the
1403 master key */
1404 if (kdf(passwd, salt, ikey, kdf_params)) {
1405 SLOGE("kdf failed");
1406 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001407 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001408
Paul Crowley14c8c072018-09-18 13:30:21 -07001409 /* Initialize the decryption engine */
1410 EVP_CIPHER_CTX_init(&d_ctx);
1411 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1412 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1413 return -1;
1414 }
1415 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1416 /* Decrypt the master key */
1417 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1418 keysize)) {
1419 return -1;
1420 }
1421 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1422 return -1;
1423 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001424
Paul Crowley14c8c072018-09-18 13:30:21 -07001425 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1426 return -1;
1427 }
1428
1429 /* Copy intermediate key if needed by params */
1430 if (intermediate_key && intermediate_key_size) {
1431 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1432 if (*intermediate_key) {
1433 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1434 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1435 }
1436 }
1437
1438 EVP_CIPHER_CTX_cleanup(&d_ctx);
1439
1440 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001441}
1442
Paul Crowley14c8c072018-09-18 13:30:21 -07001443static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001444 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001445 *kdf = scrypt_keymaster;
1446 *kdf_params = ftr;
1447 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001448 *kdf = scrypt;
1449 *kdf_params = ftr;
1450 } else {
1451 *kdf = pbkdf2;
1452 *kdf_params = NULL;
1453 }
1454}
1455
Paul Crowley14c8c072018-09-18 13:30:21 -07001456static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1457 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1458 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001459 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001460 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001461 int ret;
1462
1463 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001464 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1465 decrypted_master_key, kdf, kdf_params, intermediate_key,
1466 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001467 if (ret != 0) {
1468 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001469 }
1470
1471 return ret;
1472}
1473
Paul Crowley14c8c072018-09-18 13:30:21 -07001474static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1475 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08001476 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001477
Eric Biggers3a2f7db2019-01-16 13:05:34 -08001478 /* Get some random bits for a key and salt */
1479 if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
1480 return -1;
1481 }
1482 if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
1483 return -1;
1484 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001485
1486 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001487 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001488}
1489
Paul Crowley73be12d2020-02-03 12:22:03 -08001490static int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001491 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001492#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001493
1494 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001495 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001496 if (umount(mountpoint) == 0) {
1497 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001498 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001499
1500 if (errno == EINVAL) {
1501 /* EINVAL is returned if the directory is not a mountpoint,
1502 * i.e. there is no filesystem mounted there. So just get out.
1503 */
1504 break;
1505 }
1506
1507 err = errno;
1508
1509 /* If allowed, be increasingly aggressive before the last two retries */
1510 if (kill) {
1511 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1512 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001513 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001514 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1515 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001516 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001517 }
1518 }
1519
1520 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001521 }
1522
1523 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001524 SLOGD("unmounting %s succeeded\n", mountpoint);
1525 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001526 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001527 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1528 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1529 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001530 }
1531
1532 return rc;
1533}
1534
Paul Crowley14c8c072018-09-18 13:30:21 -07001535static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001536 // NOTE: post_fs_data results in init calling back around to vold, so all
1537 // callers to this method must be async
1538
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001539 /* Do the prep of the /data filesystem */
1540 property_set("vold.post_fs_data_done", "0");
1541 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001542 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001543
Ken Sumrallc5872692013-05-14 15:26:31 -07001544 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001545 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001546 /* We timed out to prep /data in time. Continue wait. */
1547 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001548 }
Wei Wang42e38102017-06-07 10:46:12 -07001549 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001550}
1551
Paul Crowley14c8c072018-09-18 13:30:21 -07001552static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001553 // Mark the footer as bad
1554 struct crypt_mnt_ftr crypt_ftr;
1555 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1556 SLOGE("Failed to get crypto footer - panic");
1557 return;
1558 }
1559
1560 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1561 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1562 SLOGE("Failed to set crypto footer - panic");
1563 return;
1564 }
1565}
1566
Paul Crowley14c8c072018-09-18 13:30:21 -07001567static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001568 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001569 SLOGE("Failed to mount tmpfs on data - panic");
1570 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001571 }
1572
1573 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1574 SLOGE("Failed to trigger post fs data - panic");
1575 return;
1576 }
1577
1578 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1579 SLOGE("Failed to trigger restart min framework - panic");
1580 return;
1581 }
1582}
1583
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001584/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001585static int cryptfs_restart_internal(int restart_main) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001586 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001587 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001588 static int restart_successful = 0;
1589
1590 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001591 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001592 SLOGE("Encrypted filesystem not validated, aborting");
1593 return -1;
1594 }
1595
1596 if (restart_successful) {
1597 SLOGE("System already restarted with encrypted disk, aborting");
1598 return -1;
1599 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001600
Paul Lawrencef4faa572014-01-29 13:31:03 -08001601 if (restart_main) {
1602 /* Here is where we shut down the framework. The init scripts
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001603 * start all services in one of these classes: core, early_hal, hal,
1604 * main and late_start. To get to the minimal UI for PIN entry, we
1605 * need to start core, early_hal, hal and main. When we want to
1606 * shutdown the framework again, we need to stop most of the services in
1607 * these classes, but only those services that were started after
1608 * /data was mounted. This excludes critical services like vold and
1609 * ueventd, which need to keep running. We could possible stop
1610 * even fewer services, but because we want services to pick up APEX
1611 * libraries from the real /data, restarting is better, as it makes
1612 * these devices consistent with FBE devices and lets them use the
1613 * most recent code.
1614 *
1615 * Once these services have stopped, we should be able
Paul Lawrencef4faa572014-01-29 13:31:03 -08001616 * to umount the tmpfs /data, then mount the encrypted /data.
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001617 * We then restart the class core, hal, main, and also the class
1618 * late_start.
1619 *
Paul Lawrencef4faa572014-01-29 13:31:03 -08001620 * At the moment, I've only put a few things in late_start that I know
1621 * are not needed to bring up the framework, and that also cause problems
1622 * with unmounting the tmpfs /data, but I hope to add add more services
1623 * to the late_start class as we optimize this to decrease the delay
1624 * till the user is asked for the password to the filesystem.
1625 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001626
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001627 /* The init files are setup to stop the right set of services when
1628 * vold.decrypt is set to trigger_shutdown_framework.
Paul Lawrencef4faa572014-01-29 13:31:03 -08001629 */
Martijn Coenenaec7a0a2019-04-24 10:41:11 +02001630 property_set("vold.decrypt", "trigger_shutdown_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001631 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001632
Paul Lawrencef4faa572014-01-29 13:31:03 -08001633 /* Ugh, shutting down the framework is not synchronous, so until it
1634 * can be fixed, this horrible hack will wait a moment for it all to
1635 * shut down before proceeding. Without it, some devices cannot
1636 * restart the graphics services.
1637 */
1638 sleep(2);
1639 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001640
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001641 /* Now that the framework is shutdown, we should be able to umount()
1642 * the tmpfs filesystem, and mount the real one.
1643 */
1644
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001645 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1646 if (strlen(crypto_blkdev) == 0) {
1647 SLOGE("fs_crypto_blkdev not set\n");
1648 return -1;
1649 }
1650
Paul Crowley14c8c072018-09-18 13:30:21 -07001651 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001652 /* If ro.crypto.readonly is set to 1, mount the decrypted
1653 * filesystem readonly. This is used when /data is mounted by
1654 * recovery mode.
1655 */
1656 char ro_prop[PROPERTY_VALUE_MAX];
1657 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001658 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001659 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1660 if (entry != nullptr) {
1661 entry->flags |= MS_RDONLY;
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07001662 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001663 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001664
Ken Sumralle5032c42012-04-01 23:58:44 -07001665 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001666 int retries = RETRY_MOUNT_ATTEMPTS;
1667 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001668
1669 /*
1670 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1671 * partitions in the fsck domain.
1672 */
LongPing Wei7f3ab952019-01-30 16:03:14 +08001673 if (setexeccon(android::vold::sFsckContext)) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001674 SLOGE("Failed to setexeccon");
1675 return -1;
1676 }
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001677 bool needs_cp = android::vold::cp_needsCheckpoint();
Tom Cherry4c5bde22019-01-29 14:34:01 -08001678 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001679 needs_cp)) != 0) {
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001680 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1681 /* TODO: invoke something similar to
1682 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1683 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
Paul Crowley14c8c072018-09-18 13:30:21 -07001684 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001685 if (--retries) {
1686 sleep(RETRY_MOUNT_DELAY_SECONDS);
1687 } else {
1688 /* Let's hope that a reboot clears away whatever is keeping
1689 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001690 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001691 }
1692 } else {
1693 SLOGE("Failed to mount decrypted data");
1694 cryptfs_set_corrupt();
1695 cryptfs_trigger_restart_min_framework();
1696 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001697 if (setexeccon(NULL)) {
1698 SLOGE("Failed to setexeccon");
1699 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001700 return -1;
1701 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001702 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001703 if (setexeccon(NULL)) {
1704 SLOGE("Failed to setexeccon");
1705 return -1;
1706 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001707
Ken Sumralle5032c42012-04-01 23:58:44 -07001708 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001709 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001710 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001711
1712 /* startup service classes main and late_start */
1713 property_set("vold.decrypt", "trigger_restart_framework");
1714 SLOGD("Just triggered restart_framework\n");
1715
1716 /* Give it a few moments to get started */
1717 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001718 }
1719
Ken Sumrall0cc16632011-01-18 20:32:26 -08001720 if (rc == 0) {
1721 restart_successful = 1;
1722 }
1723
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001724 return rc;
1725}
1726
Paul Crowley14c8c072018-09-18 13:30:21 -07001727int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001728 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07001729 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001730 SLOGE("cryptfs_restart not valid for file encryption:");
1731 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001732 }
1733
Paul Lawrencef4faa572014-01-29 13:31:03 -08001734 /* Call internal implementation forcing a restart of main service group */
1735 return cryptfs_restart_internal(1);
1736}
1737
Paul Crowley14c8c072018-09-18 13:30:21 -07001738static int do_crypto_complete(const char* mount_point) {
1739 struct crypt_mnt_ftr crypt_ftr;
1740 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001741
Paul Crowley14c8c072018-09-18 13:30:21 -07001742 property_get("ro.crypto.state", encrypted_state, "");
1743 if (strcmp(encrypted_state, "encrypted")) {
1744 SLOGE("not running with encryption, aborting");
1745 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001746 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001747
Paul Crowley14c8c072018-09-18 13:30:21 -07001748 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07001749 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001750 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1751 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001752
Paul Crowley14c8c072018-09-18 13:30:21 -07001753 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001754 std::string key_loc;
1755 get_crypt_info(&key_loc, nullptr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001756
Paul Crowley14c8c072018-09-18 13:30:21 -07001757 /*
1758 * Only report this error if key_loc is a file and it exists.
1759 * If the device was never encrypted, and /data is not mountable for
1760 * some reason, returning 1 should prevent the UI from presenting the
1761 * a "enter password" screen, or worse, a "press button to wipe the
1762 * device" screen.
1763 */
Tom Cherry4c5bde22019-01-29 14:34:01 -08001764 if (!key_loc.empty() && key_loc[0] == '/' && (access("key_loc", F_OK) == -1)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001765 SLOGE("master key file does not exist, aborting");
1766 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1767 } else {
1768 SLOGE("Error getting crypt footer and key\n");
1769 return CRYPTO_COMPLETE_BAD_METADATA;
1770 }
1771 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001772
Paul Crowley14c8c072018-09-18 13:30:21 -07001773 // Test for possible error flags
1774 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1775 SLOGE("Encryption process is partway completed\n");
1776 return CRYPTO_COMPLETE_PARTIAL;
1777 }
1778
1779 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1780 SLOGE("Encryption process was interrupted but cannot continue\n");
1781 return CRYPTO_COMPLETE_INCONSISTENT;
1782 }
1783
1784 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1785 SLOGE("Encryption is successful but data is corrupt\n");
1786 return CRYPTO_COMPLETE_CORRUPT;
1787 }
1788
1789 /* We passed the test! We shall diminish, and return to the west */
1790 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001791}
1792
Paul Crowley14c8c072018-09-18 13:30:21 -07001793static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
1794 const char* mount_point, const char* label) {
1795 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley81796e92020-02-07 11:27:49 -08001796 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08001797 std::string real_blkdev;
Paul Crowley14c8c072018-09-18 13:30:21 -07001798 char tmp_mount_point[64];
1799 unsigned int orig_failed_decrypt_count;
1800 int rc;
1801 int use_keymaster = 0;
1802 int upgrade = 0;
1803 unsigned char* intermediate_key = 0;
1804 size_t intermediate_key_size = 0;
1805 int N = 1 << crypt_ftr->N_factor;
1806 int r = 1 << crypt_ftr->r_factor;
1807 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001808
Paul Crowley14c8c072018-09-18 13:30:21 -07001809 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1810 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001811
Paul Crowley14c8c072018-09-18 13:30:21 -07001812 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
1813 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
1814 &intermediate_key_size)) {
1815 SLOGE("Failed to decrypt master key\n");
1816 rc = -1;
1817 goto errout;
1818 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001819 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001820
Tom Cherry4c5bde22019-01-29 14:34:01 -08001821 get_crypt_info(nullptr, &real_blkdev);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001822
Paul Crowley14c8c072018-09-18 13:30:21 -07001823 // Create crypto block device - all (non fatal) code paths
1824 // need it
Paul Crowley81796e92020-02-07 11:27:49 -08001825 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Tom Cherry4c5bde22019-01-29 14:34:01 -08001826 label, 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001827 SLOGE("Error creating decrypted block device\n");
1828 rc = -1;
1829 goto errout;
1830 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001831
Paul Crowley14c8c072018-09-18 13:30:21 -07001832 /* Work out if the problem is the password or the data */
1833 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001834
Paul Crowley14c8c072018-09-18 13:30:21 -07001835 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
1836 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
1837 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001838
Paul Crowley14c8c072018-09-18 13:30:21 -07001839 // Does the key match the crypto footer?
1840 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
1841 sizeof(scrypted_intermediate_key)) == 0) {
1842 SLOGI("Password matches");
1843 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001844 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001845 /* Try mounting the file system anyway, just in case the problem's with
1846 * the footer, not the key. */
1847 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
1848 mkdir(tmp_mount_point, 0755);
Paul Crowley81796e92020-02-07 11:27:49 -08001849 if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT,
1850 const_cast<char*>(crypto_blkdev.c_str()), tmp_mount_point)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001851 SLOGE("Error temp mounting decrypted block device\n");
1852 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001853
Paul Crowley14c8c072018-09-18 13:30:21 -07001854 rc = ++crypt_ftr->failed_decrypt_count;
1855 put_crypt_ftr_and_key(crypt_ftr);
1856 } else {
1857 /* Success! */
1858 SLOGI("Password did not match but decrypted drive mounted - continue");
1859 umount(tmp_mount_point);
1860 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001861 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001862 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001863
Paul Crowley14c8c072018-09-18 13:30:21 -07001864 if (rc == 0) {
1865 crypt_ftr->failed_decrypt_count = 0;
1866 if (orig_failed_decrypt_count != 0) {
1867 put_crypt_ftr_and_key(crypt_ftr);
1868 }
1869
1870 /* Save the name of the crypto block device
1871 * so we can mount it when restarting the framework. */
Paul Crowley81796e92020-02-07 11:27:49 -08001872 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -07001873
1874 /* Also save a the master key so we can reencrypted the key
1875 * the key when we want to change the password on it. */
1876 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
1877 saved_mount_point = strdup(mount_point);
1878 master_key_saved = 1;
1879 SLOGD("%s(): Master key saved\n", __FUNCTION__);
1880 rc = 0;
1881
1882 // Upgrade if we're not using the latest KDF.
1883 use_keymaster = keymaster_check_compatibility();
1884 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1885 // Don't allow downgrade
1886 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1887 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1888 upgrade = 1;
1889 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
1890 crypt_ftr->kdf_type = KDF_SCRYPT;
1891 upgrade = 1;
1892 }
1893
1894 if (upgrade) {
1895 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1896 crypt_ftr->master_key, crypt_ftr);
1897 if (!rc) {
1898 rc = put_crypt_ftr_and_key(crypt_ftr);
1899 }
1900 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1901
1902 // Do not fail even if upgrade failed - machine is bootable
1903 // Note that if this code is ever hit, there is a *serious* problem
1904 // since KDFs should never fail. You *must* fix the kdf before
1905 // proceeding!
1906 if (rc) {
1907 SLOGW(
1908 "Upgrade failed with error %d,"
1909 " but continuing with previous state",
1910 rc);
1911 rc = 0;
1912 }
1913 }
1914 }
1915
1916errout:
1917 if (intermediate_key) {
1918 memset(intermediate_key, 0, intermediate_key_size);
1919 free(intermediate_key);
1920 }
1921 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001922}
1923
Ken Sumrall29d8da82011-05-18 17:20:07 -07001924/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001925 * Called by vold when it's asked to mount an encrypted external
1926 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08001927 * as any metadata is been stored in a separate, small partition. We
1928 * assume it must be using our same crypt type and keysize.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001929 */
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001930int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const KeyBuffer& key,
Paul Crowley81796e92020-02-07 11:27:49 -08001931 std::string* out_crypto_blkdev) {
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001932 if (key.size() != cryptfs_get_keysize()) {
1933 SLOGE("Raw keysize %zu does not match crypt keysize %" PRIu32, key.size(),
1934 cryptfs_get_keysize());
1935 return -1;
1936 }
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001937 uint64_t nr_sec = 0;
1938 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001939 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001940 return -1;
1941 }
1942
Jeff Sharkey9c484982015-03-31 10:35:33 -07001943 struct crypt_mnt_ftr ext_crypt_ftr;
1944 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1945 ext_crypt_ftr.fs_size = nr_sec;
Greg Kaiser57f9af62018-02-16 13:13:58 -08001946 ext_crypt_ftr.keysize = cryptfs_get_keysize();
Paul Crowley14c8c072018-09-18 13:30:21 -07001947 strlcpy((char*)ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001948 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07001949 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07001950 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07001951 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
1952 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001953
Paul Crowley3d98f5d2020-02-07 11:49:09 -08001954 return create_crypto_blk_dev(&ext_crypt_ftr, reinterpret_cast<const unsigned char*>(key.data()),
1955 real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001956}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001957
Paul Crowley14c8c072018-09-18 13:30:21 -07001958int cryptfs_crypto_complete(void) {
1959 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001960}
1961
Paul Crowley14c8c072018-09-18 13:30:21 -07001962int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001963 char encrypted_state[PROPERTY_VALUE_MAX];
1964 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07001965 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
1966 SLOGE(
1967 "encrypted fs already validated or not running with encryption,"
1968 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001969 return -1;
1970 }
1971
1972 if (get_crypt_ftr_and_key(crypt_ftr)) {
1973 SLOGE("Error getting crypt footer and key");
1974 return -1;
1975 }
1976
1977 return 0;
1978}
1979
Paul Crowley14c8c072018-09-18 13:30:21 -07001980int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001981 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07001982 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001983 SLOGE("cryptfs_check_passwd not valid for file encryption");
1984 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001985 }
1986
Paul Lawrencef4faa572014-01-29 13:31:03 -08001987 struct crypt_mnt_ftr crypt_ftr;
1988 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001989
Paul Lawrencef4faa572014-01-29 13:31:03 -08001990 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001991 if (rc) {
1992 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001993 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001994 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001995
Paul Crowley14c8c072018-09-18 13:30:21 -07001996 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001997 if (rc) {
1998 SLOGE("Password did not match");
1999 return rc;
2000 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002001
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002002 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2003 // Here we have a default actual password but a real password
2004 // we must test against the scrypted value
2005 // First, we must delete the crypto block device that
2006 // test_mount_encrypted_fs leaves behind as a side effect
2007 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07002008 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
2009 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002010 if (rc) {
2011 SLOGE("Default password did not match on reboot encryption");
2012 return rc;
2013 }
2014
2015 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2016 put_crypt_ftr_and_key(&crypt_ftr);
2017 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
2018 if (rc) {
2019 SLOGE("Could not change password on reboot encryption");
2020 return rc;
2021 }
2022 }
2023
2024 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002025 cryptfs_clear_password();
2026 password = strdup(passwd);
2027 struct timespec now;
2028 clock_gettime(CLOCK_BOOTTIME, &now);
2029 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002030 }
2031
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002032 return rc;
2033}
2034
Paul Crowley14c8c072018-09-18 13:30:21 -07002035int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002036 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002037 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002038 char encrypted_state[PROPERTY_VALUE_MAX];
2039 int rc;
2040
2041 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002042 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002043 SLOGE("device not encrypted, aborting");
2044 return -2;
2045 }
2046
2047 if (!master_key_saved) {
2048 SLOGE("encrypted fs not yet mounted, aborting");
2049 return -1;
2050 }
2051
2052 if (!saved_mount_point) {
2053 SLOGE("encrypted fs failed to save mount point, aborting");
2054 return -1;
2055 }
2056
Ken Sumrall160b4d62013-04-22 12:15:39 -07002057 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002058 SLOGE("Error getting crypt footer and key\n");
2059 return -1;
2060 }
2061
2062 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2063 /* If the device has no password, then just say the password is valid */
2064 rc = 0;
2065 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002066 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002067 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2068 /* They match, the password is correct */
2069 rc = 0;
2070 } else {
2071 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2072 sleep(1);
2073 rc = 1;
2074 }
2075 }
2076
2077 return rc;
2078}
2079
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002080/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser57f9af62018-02-16 13:13:58 -08002081 * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002082 * Presumably, at a minimum, the caller will update the
2083 * filesystem size and crypto_type_name after calling this function.
2084 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002085static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002086 off64_t off;
2087
2088 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002089 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002090 ftr->major_version = CURRENT_MAJOR_VERSION;
2091 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002092 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser57f9af62018-02-16 13:13:58 -08002093 ftr->keysize = cryptfs_get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07002094
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002095 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002096 case 1:
2097 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2098 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002099
Paul Crowley14c8c072018-09-18 13:30:21 -07002100 case 0:
2101 ftr->kdf_type = KDF_SCRYPT;
2102 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002103
Paul Crowley14c8c072018-09-18 13:30:21 -07002104 default:
2105 SLOGE("keymaster_check_compatibility failed");
2106 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002107 }
2108
Kenny Rootc4c70f12013-06-14 12:11:38 -07002109 get_device_scrypt_params(ftr);
2110
Ken Sumrall160b4d62013-04-22 12:15:39 -07002111 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2112 if (get_crypt_ftr_info(NULL, &off) == 0) {
2113 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002114 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002115 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002116
2117 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002118}
2119
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002120#define FRAMEWORK_BOOT_WAIT 60
2121
Paul Crowley14c8c072018-09-18 13:30:21 -07002122static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2123 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002124 if (fd == -1) {
2125 SLOGE("Error opening file %s", filename);
2126 return -1;
2127 }
2128
2129 char block[CRYPT_INPLACE_BUFSIZE];
2130 memset(block, 0, sizeof(block));
2131 if (unix_read(fd, block, sizeof(block)) < 0) {
2132 SLOGE("Error reading file %s", filename);
2133 close(fd);
2134 return -1;
2135 }
2136
2137 close(fd);
2138
2139 SHA256_CTX c;
2140 SHA256_Init(&c);
2141 SHA256_Update(&c, block, sizeof(block));
2142 SHA256_Final(buf, &c);
2143
2144 return 0;
2145}
2146
Paul Crowley81796e92020-02-07 11:27:49 -08002147static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, const char* crypto_blkdev,
2148 const char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002149 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002150 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002151
Paul Lawrence87999172014-02-20 12:21:31 -08002152 /* The size of the userdata partition, and add in the vold volumes below */
2153 tot_encryption_size = crypt_ftr->fs_size;
2154
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002155 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002156 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002157
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002158 if (rc == ENABLE_INPLACE_ERR_DEV) {
2159 /* Hack for b/17898962 */
2160 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2161 cryptfs_reboot(RebootType::reboot);
2162 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002163
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002164 if (!rc) {
2165 crypt_ftr->encrypted_upto = cur_encryption_done;
2166 }
Paul Lawrence87999172014-02-20 12:21:31 -08002167
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002168 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2169 /* The inplace routine never actually sets the progress to 100% due
2170 * to the round down nature of integer division, so set it here */
2171 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002172 }
2173
2174 return rc;
2175}
2176
Paul Crowleyb64933a2017-10-31 08:25:55 -07002177static int vold_unmountAll(void) {
2178 VolumeManager* vm = VolumeManager::Instance();
2179 return vm->unmountAll();
2180}
2181
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002182int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Crowley81796e92020-02-07 11:27:49 -08002183 std::string crypto_blkdev;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002184 std::string real_blkdev;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002185 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002186 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002187 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002188 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002189 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002190 char lockid[32] = {0};
Tom Cherry4c5bde22019-01-29 14:34:01 -08002191 std::string key_loc;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002192 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002193 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002194 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002195 bool onlyCreateHeader = false;
Tri Vo15bbe222019-06-21 12:21:48 -07002196 std::unique_ptr<android::wakelock::WakeLock> wakeLock = nullptr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002197
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002198 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002199 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2200 /* An encryption was underway and was interrupted */
2201 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2202 crypt_ftr.encrypted_upto = 0;
2203 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002204
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002205 /* At this point, we are in an inconsistent state. Until we successfully
2206 complete encryption, a reboot will leave us broken. So mark the
2207 encryption failed in case that happens.
2208 On successfully completing encryption, remove this flag */
2209 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002210
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002211 put_crypt_ftr_and_key(&crypt_ftr);
2212 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2213 if (!check_ftr_sha(&crypt_ftr)) {
2214 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2215 put_crypt_ftr_and_key(&crypt_ftr);
2216 goto error_unencrypted;
2217 }
2218
2219 /* Doing a reboot-encryption*/
2220 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2221 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2222 rebootEncryption = true;
2223 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002224 } else {
2225 // We don't want to accidentally reference invalid data.
2226 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002227 }
2228
2229 property_get("ro.crypto.state", encrypted_state, "");
2230 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2231 SLOGE("Device is already running encrypted, aborting");
2232 goto error_unencrypted;
2233 }
2234
Tom Cherry4c5bde22019-01-29 14:34:01 -08002235 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002236
Ken Sumrall3ed82362011-01-28 23:31:16 -08002237 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002238 uint64_t nr_sec;
2239 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002240 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Ken Sumrall3ed82362011-01-28 23:31:16 -08002241 goto error_unencrypted;
2242 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002243
2244 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002245 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002246 uint64_t fs_size_sec, max_fs_size_sec;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002247 fs_size_sec = get_fs_size(real_blkdev.c_str());
2248 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev.data());
Daniel Rosenberge82df162014-08-15 22:19:23 +00002249
Paul Lawrence87999172014-02-20 12:21:31 -08002250 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002251
2252 if (fs_size_sec > max_fs_size_sec) {
2253 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2254 goto error_unencrypted;
2255 }
2256 }
2257
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002258 /* Get a wakelock as this may take a while, and we don't want the
2259 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2260 * wants to keep the screen on, it can grab a full wakelock.
2261 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002262 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Tri Vo15bbe222019-06-21 12:21:48 -07002263 wakeLock = std::make_unique<android::wakelock::WakeLock>(lockid);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002264
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002265 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002266 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002267 */
2268 property_set("vold.decrypt", "trigger_shutdown_framework");
2269 SLOGD("Just asked init to shut down class main\n");
2270
Jeff Sharkey9c484982015-03-31 10:35:33 -07002271 /* Ask vold to unmount all devices that it manages */
2272 if (vold_unmountAll()) {
2273 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002274 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002275
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002276 /* no_ui means we are being called from init, not settings.
2277 Now we always reboot from settings, so !no_ui means reboot
2278 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002279 if (!no_ui) {
2280 /* Try fallback, which is to reboot and try there */
2281 onlyCreateHeader = true;
2282 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2283 if (breadcrumb == 0) {
2284 SLOGE("Failed to create breadcrumb file");
2285 goto error_shutting_down;
2286 }
2287 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002288 }
2289
2290 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002291 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002292 /* Now that /data is unmounted, we need to mount a tmpfs
2293 * /data, set a property saying we're doing inplace encryption,
2294 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002295 */
xzj7e38a3a2018-10-12 10:17:11 +08002296 wait_and_unmount(DATA_MNT_POINT, true);
Ken Sumralle5032c42012-04-01 23:58:44 -07002297 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002298 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002299 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002300 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002301 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002302
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002303 /* restart the framework. */
2304 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002305 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002306
Ken Sumrall92736ef2012-10-17 20:57:14 -07002307 /* Ugh, shutting down the framework is not synchronous, so until it
2308 * can be fixed, this horrible hack will wait a moment for it all to
2309 * shut down before proceeding. Without it, some devices cannot
2310 * restart the graphics services.
2311 */
2312 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002313 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002314
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002315 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002316 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002317 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002318 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2319 goto error_shutting_down;
2320 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002321
Tom Cherry4c5bde22019-01-29 14:34:01 -08002322 if (key_loc == KEY_IN_FOOTER) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002323 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002324 } else {
2325 crypt_ftr.fs_size = nr_sec;
2326 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002327 /* At this point, we are in an inconsistent state. Until we successfully
2328 complete encryption, a reboot will leave us broken. So mark the
2329 encryption failed in case that happens.
2330 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002331 if (onlyCreateHeader) {
2332 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2333 } else {
2334 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2335 }
Paul Lawrence87999172014-02-20 12:21:31 -08002336 crypt_ftr.crypt_type = crypt_type;
Paul Crowley14c8c072018-09-18 13:30:21 -07002337 strlcpy((char*)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
2338 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002339
Paul Lawrence87999172014-02-20 12:21:31 -08002340 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002341 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2342 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002343 SLOGE("Cannot create encrypted master key\n");
2344 goto error_shutting_down;
2345 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002346
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002347 /* Replace scrypted intermediate key if we are preparing for a reboot */
2348 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002349 unsigned char fake_master_key[MAX_KEY_LEN];
2350 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002351 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002352 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
2353 &crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002354 }
2355
Paul Lawrence87999172014-02-20 12:21:31 -08002356 /* Write the key to the end of the partition */
2357 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002358
Paul Lawrence87999172014-02-20 12:21:31 -08002359 /* If any persistent data has been remembered, save it.
2360 * If none, create a valid empty table and save that.
2361 */
2362 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002363 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2364 if (pdata) {
2365 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2366 persist_data = pdata;
2367 }
Paul Lawrence87999172014-02-20 12:21:31 -08002368 }
2369 if (persist_data) {
2370 save_persistent_data();
2371 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002372 }
2373
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002374 if (onlyCreateHeader) {
2375 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002376 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002377 }
2378
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002379 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002380 /* startup service classes main and late_start */
2381 property_set("vold.decrypt", "trigger_restart_min_framework");
2382 SLOGD("Just triggered restart_min_framework\n");
2383
2384 /* OK, the framework is restarted and will soon be showing a
2385 * progress bar. Time to setup an encrypted mapping, and
2386 * either write a new filesystem, or encrypt in place updating
2387 * the progress bar as we work.
2388 */
2389 }
2390
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002391 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Paul Crowley81796e92020-02-07 11:27:49 -08002392 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002393 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002394
Paul Lawrence87999172014-02-20 12:21:31 -08002395 /* If we are continuing, check checksums match */
2396 rc = 0;
2397 if (previously_encrypted_upto) {
2398 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
Paul Crowley81796e92020-02-07 11:27:49 -08002399 rc = cryptfs_SHA256_fileblock(crypto_blkdev.c_str(), hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002400
Paul Crowley14c8c072018-09-18 13:30:21 -07002401 if (!rc &&
2402 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002403 SLOGE("Checksums do not match - trigger wipe");
2404 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002405 }
2406 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002407
Paul Lawrence87999172014-02-20 12:21:31 -08002408 if (!rc) {
Paul Crowley81796e92020-02-07 11:27:49 -08002409 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev.c_str(), real_blkdev.data(),
Paul Lawrence87999172014-02-20 12:21:31 -08002410 previously_encrypted_upto);
2411 }
2412
2413 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002414 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley81796e92020-02-07 11:27:49 -08002415 rc = cryptfs_SHA256_fileblock(crypto_blkdev.c_str(), crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002416 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002417 SLOGE("Error calculating checksum for continuing encryption");
2418 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002419 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002420 }
2421
2422 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002423 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002424
Paul Crowley14c8c072018-09-18 13:30:21 -07002425 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002426 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002427 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002428
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002429 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002430 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2431 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002432 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002433 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002434
Paul Lawrence6bfed202014-07-28 12:47:22 -07002435 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002436
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002437 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2438 char value[PROPERTY_VALUE_MAX];
2439 property_get("ro.crypto.state", value, "");
2440 if (!strcmp(value, "")) {
2441 /* default encryption - continue first boot sequence */
2442 property_set("ro.crypto.state", "encrypted");
2443 property_set("ro.crypto.type", "block");
Tri Vo15bbe222019-06-21 12:21:48 -07002444 wakeLock.reset(nullptr);
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002445 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2446 // Bring up cryptkeeper that will check the password and set it
2447 property_set("vold.decrypt", "trigger_shutdown_framework");
2448 sleep(2);
2449 property_set("vold.encrypt_progress", "");
2450 cryptfs_trigger_restart_min_framework();
2451 } else {
2452 cryptfs_check_passwd(DEFAULT_PASSWORD);
2453 cryptfs_restart_internal(1);
2454 }
2455 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002456 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002457 sleep(2); /* Give the UI a chance to show 100% progress */
2458 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002459 }
Paul Lawrence87999172014-02-20 12:21:31 -08002460 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002461 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002462 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002463 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002464 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002465 char value[PROPERTY_VALUE_MAX];
2466
Ken Sumrall319369a2012-06-27 16:30:18 -07002467 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002468 if (!strcmp(value, "1")) {
2469 /* wipe data if encryption failed */
2470 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002471 std::string err;
2472 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002473 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002474 if (!write_bootloader_message(options, &err)) {
2475 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002476 }
Josh Gaofec44372017-08-28 13:22:55 -07002477 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002478 } else {
2479 /* set property to trigger dialog */
2480 property_set("vold.encrypt_progress", "error_partially_encrypted");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002481 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002482 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002483 }
2484
Ken Sumrall3ed82362011-01-28 23:31:16 -08002485 /* hrm, the encrypt step claims success, but the reboot failed.
2486 * This should not happen.
2487 * Set the property and return. Hope the framework can deal with it.
2488 */
2489 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002490 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002491
2492error_unencrypted:
2493 property_set("vold.encrypt_progress", "error_not_encrypted");
2494 return -1;
2495
2496error_shutting_down:
2497 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2498 * but the framework is stopped and not restarted to show the error, so it's up to
2499 * vold to restart the system.
2500 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002501 SLOGE(
2502 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2503 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002504 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002505
2506 /* shouldn't get here */
2507 property_set("vold.encrypt_progress", "error_shutting_down");
2508 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002509}
2510
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002511int cryptfs_enable(int type, const char* passwd, int no_ui) {
2512 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002513}
2514
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002515int cryptfs_enable_default(int no_ui) {
2516 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002517}
2518
Paul Crowley14c8c072018-09-18 13:30:21 -07002519int cryptfs_changepw(int crypt_type, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002520 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002521 SLOGE("cryptfs_changepw not valid for file encryption");
2522 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002523 }
2524
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002525 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002526 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002527
2528 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002529 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002530 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002531 return -1;
2532 }
2533
Paul Lawrencef4faa572014-01-29 13:31:03 -08002534 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2535 SLOGE("Invalid crypt_type %d", crypt_type);
2536 return -1;
2537 }
2538
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002539 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002540 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002541 SLOGE("Error getting crypt footer and key");
2542 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002543 }
2544
Paul Lawrencef4faa572014-01-29 13:31:03 -08002545 crypt_ftr.crypt_type = crypt_type;
2546
Paul Crowley14c8c072018-09-18 13:30:21 -07002547 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
2548 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002549 if (rc) {
2550 SLOGE("Encrypt master key failed: %d", rc);
2551 return -1;
2552 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002553 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002554 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002555
2556 return 0;
2557}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002558
Rubin Xu85c01f92014-10-13 12:49:54 +01002559static unsigned int persist_get_max_entries(int encrypted) {
2560 struct crypt_mnt_ftr crypt_ftr;
2561 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01002562
2563 /* If encrypted, use the values from the crypt_ftr, otherwise
2564 * use the values for the current spec.
2565 */
2566 if (encrypted) {
2567 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xuf83cc612018-10-09 16:13:38 +01002568 /* Something is wrong, assume no space for entries */
2569 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002570 }
2571 dsize = crypt_ftr.persist_data_size;
2572 } else {
2573 dsize = CRYPT_PERSIST_DATA_SIZE;
2574 }
2575
Rubin Xuf83cc612018-10-09 16:13:38 +01002576 if (dsize > sizeof(struct crypt_persist_data)) {
2577 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
2578 } else {
2579 return 0;
2580 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002581}
2582
Paul Crowley14c8c072018-09-18 13:30:21 -07002583static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002584 unsigned int i;
2585
2586 if (persist_data == NULL) {
2587 return -1;
2588 }
2589 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2590 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2591 /* We found it! */
2592 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2593 return 0;
2594 }
2595 }
2596
2597 return -1;
2598}
2599
Paul Crowley14c8c072018-09-18 13:30:21 -07002600static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002601 unsigned int i;
2602 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002603 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002604
2605 if (persist_data == NULL) {
2606 return -1;
2607 }
2608
Rubin Xu85c01f92014-10-13 12:49:54 +01002609 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002610
2611 num = persist_data->persist_valid_entries;
2612
2613 for (i = 0; i < num; i++) {
2614 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2615 /* We found an existing entry, update it! */
2616 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2617 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2618 return 0;
2619 }
2620 }
2621
2622 /* We didn't find it, add it to the end, if there is room */
2623 if (persist_data->persist_valid_entries < max_persistent_entries) {
2624 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2625 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2626 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2627 persist_data->persist_valid_entries++;
2628 return 0;
2629 }
2630
2631 return -1;
2632}
2633
Rubin Xu85c01f92014-10-13 12:49:54 +01002634/**
2635 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2636 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2637 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002638int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002639 std::string key_ = key;
2640 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002641
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002642 std::string parsed_field;
2643 unsigned parsed_index;
2644
2645 std::string::size_type split = key_.find_last_of('_');
2646 if (split == std::string::npos) {
2647 parsed_field = key_;
2648 parsed_index = 0;
2649 } else {
2650 parsed_field = key_.substr(0, split);
2651 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002652 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002653
2654 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002655}
2656
2657/*
2658 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2659 * remaining entries starting from index will be deleted.
2660 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2661 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2662 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2663 *
2664 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002665static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002666 unsigned int i;
2667 unsigned int j;
2668 unsigned int num;
2669
2670 if (persist_data == NULL) {
2671 return PERSIST_DEL_KEY_ERROR_OTHER;
2672 }
2673
2674 num = persist_data->persist_valid_entries;
2675
Paul Crowley14c8c072018-09-18 13:30:21 -07002676 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01002677 // Filter out to-be-deleted entries in place.
2678 for (i = 0; i < num; i++) {
2679 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2680 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2681 j++;
2682 }
2683 }
2684
2685 if (j < num) {
2686 persist_data->persist_valid_entries = j;
2687 // Zeroise the remaining entries
2688 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2689 return PERSIST_DEL_KEY_OK;
2690 } else {
2691 // Did not find an entry matching the given fieldname
2692 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2693 }
2694}
2695
Paul Crowley14c8c072018-09-18 13:30:21 -07002696static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002697 unsigned int i;
2698 unsigned int count;
2699
2700 if (persist_data == NULL) {
2701 return -1;
2702 }
2703
2704 count = 0;
2705 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2706 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2707 count++;
2708 }
2709 }
2710
2711 return count;
2712}
2713
Ken Sumrall160b4d62013-04-22 12:15:39 -07002714/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002715int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07002716 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002717 SLOGE("Cannot get field when file encrypted");
2718 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002719 }
2720
Ken Sumrall160b4d62013-04-22 12:15:39 -07002721 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002722 /* CRYPTO_GETFIELD_OK is success,
2723 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2724 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2725 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002726 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002727 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2728 int i;
2729 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002730
2731 if (persist_data == NULL) {
2732 load_persistent_data();
2733 if (persist_data == NULL) {
2734 SLOGE("Getfield error, cannot load persistent data");
2735 goto out;
2736 }
2737 }
2738
Rubin Xu85c01f92014-10-13 12:49:54 +01002739 // Read value from persistent entries. If the original value is split into multiple entries,
2740 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002741 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002742 // 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 -07002743 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002744 // value too small
2745 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2746 goto out;
2747 }
2748 rc = CRYPTO_GETFIELD_OK;
2749
2750 for (i = 1; /* break explicitly */; i++) {
2751 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07002752 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002753 // If the fieldname is very long, we stop as soon as it begins to overflow the
2754 // maximum field length. At this point we have in fact fully read out the original
2755 // value because cryptfs_setfield would not allow fields with longer names to be
2756 // written in the first place.
2757 break;
2758 }
2759 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002760 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2761 // value too small.
2762 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2763 goto out;
2764 }
Rubin Xu85c01f92014-10-13 12:49:54 +01002765 } else {
2766 // Exhaust all entries.
2767 break;
2768 }
2769 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002770 } else {
2771 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002772 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002773 }
2774
2775out:
2776 return rc;
2777}
2778
2779/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07002780int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07002781 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002782 SLOGE("Cannot set field when file encrypted");
2783 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002784 }
2785
Ken Sumrall160b4d62013-04-22 12:15:39 -07002786 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002787 /* 0 is success, negative values are error */
2788 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002789 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002790 unsigned int field_id;
2791 char temp_field[PROPERTY_KEY_MAX];
2792 unsigned int num_entries;
2793 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002794
2795 if (persist_data == NULL) {
2796 load_persistent_data();
2797 if (persist_data == NULL) {
2798 SLOGE("Setfield error, cannot load persistent data");
2799 goto out;
2800 }
2801 }
2802
2803 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002804 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002805 encrypted = 1;
2806 }
2807
Rubin Xu85c01f92014-10-13 12:49:54 +01002808 // Compute the number of entries required to store value, each entry can store up to
2809 // (PROPERTY_VALUE_MAX - 1) chars
2810 if (strlen(value) == 0) {
2811 // Empty value also needs one entry to store.
2812 num_entries = 1;
2813 } else {
2814 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2815 }
2816
2817 max_keylen = strlen(fieldname);
2818 if (num_entries > 1) {
2819 // Need an extra "_%d" suffix.
2820 max_keylen += 1 + log10(num_entries);
2821 }
2822 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2823 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002824 goto out;
2825 }
2826
Rubin Xu85c01f92014-10-13 12:49:54 +01002827 // Make sure we have enough space to write the new value
2828 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2829 persist_get_max_entries(encrypted)) {
2830 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2831 goto out;
2832 }
2833
2834 // Now that we know persist_data has enough space for value, let's delete the old field first
2835 // to make up space.
2836 persist_del_keys(fieldname, 0);
2837
2838 if (persist_set_key(fieldname, value, encrypted)) {
2839 // fail to set key, should not happen as we have already checked the available space
2840 SLOGE("persist_set_key() error during setfield()");
2841 goto out;
2842 }
2843
2844 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002845 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002846
2847 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2848 // fail to set key, should not happen as we have already checked the available space.
2849 SLOGE("persist_set_key() error during setfield()");
2850 goto out;
2851 }
2852 }
2853
Ken Sumrall160b4d62013-04-22 12:15:39 -07002854 /* If we are running encrypted, save the persistent data now */
2855 if (encrypted) {
2856 if (save_persistent_data()) {
2857 SLOGE("Setfield error, cannot save persistent data");
2858 goto out;
2859 }
2860 }
2861
Rubin Xu85c01f92014-10-13 12:49:54 +01002862 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002863
2864out:
2865 return rc;
2866}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002867
2868/* Checks userdata. Attempt to mount the volume if default-
2869 * encrypted.
2870 * On success trigger next init phase and return 0.
2871 * Currently do not handle failure - see TODO below.
2872 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002873int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002874 int crypt_type = cryptfs_get_password_type();
2875 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2876 SLOGE("Bad crypt type - error");
2877 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002878 SLOGD(
2879 "Password is not default - "
2880 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07002881 property_set("vold.decrypt", "trigger_restart_min_framework");
2882 return 0;
2883 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2884 SLOGD("Password is default - restarting filesystem");
2885 cryptfs_restart_internal(0);
2886 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002887 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002888 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002889 }
2890
Paul Lawrence6bfed202014-07-28 12:47:22 -07002891 /** Corrupt. Allow us to boot into framework, which will detect bad
2892 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002893 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002894 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002895 return 0;
2896}
2897
2898/* Returns type of the password, default, pattern, pin or password.
2899 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002900int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07002901 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002902 SLOGE("cryptfs_get_password_type not valid for file encryption");
2903 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002904 }
2905
Paul Lawrencef4faa572014-01-29 13:31:03 -08002906 struct crypt_mnt_ftr crypt_ftr;
2907
2908 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2909 SLOGE("Error getting crypt footer and key\n");
2910 return -1;
2911 }
2912
Paul Lawrence6bfed202014-07-28 12:47:22 -07002913 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2914 return -1;
2915 }
2916
Paul Lawrencef4faa572014-01-29 13:31:03 -08002917 return crypt_ftr.crypt_type;
2918}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002919
Paul Crowley14c8c072018-09-18 13:30:21 -07002920const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07002921 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002922 SLOGE("cryptfs_get_password not valid for file encryption");
2923 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002924 }
2925
Paul Lawrence399317e2014-03-10 13:20:50 -07002926 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002927 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002928 if (now.tv_sec < password_expiry_time) {
2929 return password;
2930 } else {
2931 cryptfs_clear_password();
2932 return 0;
2933 }
2934}
2935
Paul Crowley14c8c072018-09-18 13:30:21 -07002936void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07002937 if (password) {
2938 size_t len = strlen(password);
2939 memset(password, 0, len);
2940 free(password);
2941 password = 0;
2942 password_expiry_time = 0;
2943 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002944}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002945
Paul Crowley14c8c072018-09-18 13:30:21 -07002946int cryptfs_isConvertibleToFBE() {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002947 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
2948 return entry && entry->fs_mgr_flags.force_fde_or_fbe;
Paul Lawrence0c247462015-10-29 10:30:57 -07002949}