blob: c5024aeb35f37690475c029e58911f32af4deabb [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
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
23#include <sys/types.h>
Ken Sumralle550f782013-08-20 13:48:23 -070024#include <sys/wait.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080025#include <sys/stat.h>
Paul Lawrencef4faa572014-01-29 13:31:03 -080026#include <ctype.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080027#include <fcntl.h>
Elliott Hughes73737162014-06-25 17:27:42 -070028#include <inttypes.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080029#include <unistd.h>
30#include <stdio.h>
31#include <sys/ioctl.h>
32#include <linux/dm-ioctl.h>
33#include <libgen.h>
34#include <stdlib.h>
35#include <sys/param.h>
36#include <string.h>
37#include <sys/mount.h>
38#include <openssl/evp.h>
Adam Langley41405bb2015-01-22 16:45:28 -080039#include <openssl/sha.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080040#include <errno.h>
Paul Crowley3b71fc52017-10-09 10:55:21 -070041#include <ext4_utils/ext4_crypt.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070042#include <ext4_utils/ext4_utils.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070043#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070044#include <fs_mgr.h>
Paul Lawrence9c58a872014-09-30 09:12:51 -070045#include <time.h>
Rubin Xu85c01f92014-10-13 12:49:54 +010046#include <math.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080047#include <selinux/selinux.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080048#include "cryptfs.h"
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080049#include "secontext.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080050#define LOG_TAG "Cryptfs"
51#include "cutils/log.h"
52#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070053#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080054#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070055#include <logwrap/logwrap.h>
Paul Crowley63c18d32016-02-10 14:02:47 +000056#include "ScryptParameters.h"
Ken Sumrall29d8da82011-05-18 17:20:07 -070057#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070058#include "VoldUtil.h"
Paul Lawrence731a7a22015-04-28 22:14:15 +000059#include "Ext4Crypt.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000060#include "f2fs_sparseblock.h"
Paul Crowleyf71ace32016-06-02 11:01:19 -070061#include "EncryptInplace.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080062#include "Process.h"
Janis Danisevskis015ec302017-01-31 11:31:08 +000063#include "Keymaster.h"
Wei Wang4375f1b2017-02-24 17:43:01 -080064#include "android-base/properties.h"
Yabin Cui1fb59662016-06-24 14:48:49 -070065#include <bootloader_message/bootloader_message.h>
Wei Wang4375f1b2017-02-24 17:43:01 -080066extern "C" {
67#include <crypto_scrypt.h>
68}
Mark Salyzyn3e971272014-01-21 13:27:04 -080069
Mark Salyzyn5eecc442014-02-12 14:16:14 -080070#define UNUSED __attribute__((unused))
71
Ken Sumrall8f869aa2010-12-03 03:47:09 -080072#define DM_CRYPT_BUF_SIZE 4096
73
Jason parks70a4b3f2011-01-28 10:10:47 -060074#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -080075
76constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
77constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
78constexpr size_t INTERMEDIATE_BUF_SIZE =
79 (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
80
81// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
82static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN,
83 "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -060084
Ken Sumrall29d8da82011-05-18 17:20:07 -070085#define KEY_IN_FOOTER "footer"
86
Paul Lawrence3bd36d52015-06-09 13:37:44 -070087#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080088
Paul Lawrence3d99eba2015-11-20 07:07:19 -080089#define CRYPTO_BLOCK_DEVICE "userdata"
90
91#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
92
Ken Sumrall29d8da82011-05-18 17:20:07 -070093#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070094#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070095
Ken Sumralle919efe2012-09-29 17:07:41 -070096#define TABLE_LOAD_RETRIES 10
97
Shawn Willden47ba10d2014-09-03 17:07:06 -060098#define RSA_KEY_SIZE 2048
99#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
100#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600101#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700102
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700103#define RETRY_MOUNT_ATTEMPTS 10
104#define RETRY_MOUNT_DELAY_SECONDS 1
105
Paul Crowley5afbc622017-11-27 09:42:17 -0800106#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
107
Paul Crowley73473332017-11-21 15:43:51 -0800108static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
109
Greg Kaiser59ad0182018-02-16 13:01:36 -0800110static unsigned char saved_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -0700111static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -0600112static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700113static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800114
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700115/* Should we use keymaster? */
116static int keymaster_check_compatibility()
117{
Janis Danisevskis015ec302017-01-31 11:31:08 +0000118 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700119}
120
121/* Create a new keymaster key and store it in this footer */
122static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
123{
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800124 if (ftr->keymaster_blob_size) {
125 SLOGI("Already have key");
126 return 0;
127 }
128
Janis Danisevskis015ec302017-01-31 11:31:08 +0000129 int rc = keymaster_create_key_for_cryptfs_scrypt(RSA_KEY_SIZE, RSA_EXPONENT,
130 KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
131 &ftr->keymaster_blob_size);
132 if (rc) {
133 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800134 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000135 ftr->keymaster_blob_size = 0;
136 }
137 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700138 return -1;
139 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000140 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700141}
142
Shawn Willdene17a9c42014-09-08 13:04:08 -0600143/* This signs the given object using the keymaster key. */
144static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600145 const unsigned char *object,
146 const size_t object_size,
147 unsigned char **signature,
148 size_t *signature_size)
149{
Shawn Willden47ba10d2014-09-03 17:07:06 -0600150 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600151 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600152 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600153
Shawn Willdene17a9c42014-09-08 13:04:08 -0600154 // To sign a message with RSA, the message must satisfy two
155 // constraints:
156 //
157 // 1. The message, when interpreted as a big-endian numeric value, must
158 // be strictly less than the public modulus of the RSA key. Note
159 // that because the most significant bit of the public modulus is
160 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
161 // key), an n-bit message with most significant bit 0 always
162 // satisfies this requirement.
163 //
164 // 2. The message must have the same length in bits as the public
165 // modulus of the RSA key. This requirement isn't mathematically
166 // necessary, but is necessary to ensure consistency in
167 // implementations.
168 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600169 case KDF_SCRYPT_KEYMASTER:
170 // This ensures the most significant byte of the signed message
171 // is zero. We could have zero-padded to the left instead, but
172 // this approach is slightly more robust against changes in
173 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600174 // so) because we really should be using a proper deterministic
175 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800176 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600177 SLOGI("Signing safely-padded object");
178 break;
179 default:
180 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000181 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600182 }
Paul Crowley73473332017-11-21 15:43:51 -0800183 for (;;) {
184 auto result = keymaster_sign_object_for_cryptfs_scrypt(
185 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
186 to_sign_size, signature, signature_size);
187 switch (result) {
188 case KeymasterSignResult::ok:
189 return 0;
190 case KeymasterSignResult::upgrade:
191 break;
192 default:
193 return -1;
194 }
195 SLOGD("Upgrading key");
196 if (keymaster_upgrade_key_for_cryptfs_scrypt(
197 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
198 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
199 &ftr->keymaster_blob_size) != 0) {
200 SLOGE("Failed to upgrade key");
201 return -1;
202 }
203 if (put_crypt_ftr_and_key(ftr) != 0) {
204 SLOGE("Failed to write upgraded key to disk");
205 }
206 SLOGD("Key upgraded successfully");
207 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600208}
209
Paul Lawrence399317e2014-03-10 13:20:50 -0700210/* Store password when userdata is successfully decrypted and mounted.
211 * Cleared by cryptfs_clear_password
212 *
213 * To avoid a double prompt at boot, we need to store the CryptKeeper
214 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
215 * Since the entire framework is torn down and rebuilt after encryption,
216 * we have to use a daemon or similar to store the password. Since vold
217 * is secured against IPC except from system processes, it seems a reasonable
218 * place to store this.
219 *
220 * password should be cleared once it has been used.
221 *
222 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800223 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700224static char* password = 0;
225static int password_expiry_time = 0;
226static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800227
Josh Gaofec44372017-08-28 13:22:55 -0700228enum class RebootType {reboot, recovery, shutdown};
229static void cryptfs_reboot(RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700230{
Josh Gaofec44372017-08-28 13:22:55 -0700231 switch (rt) {
232 case RebootType::reboot:
Paul Lawrence87999172014-02-20 12:21:31 -0800233 property_set(ANDROID_RB_PROPERTY, "reboot");
234 break;
235
Josh Gaofec44372017-08-28 13:22:55 -0700236 case RebootType::recovery:
Paul Lawrence87999172014-02-20 12:21:31 -0800237 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
238 break;
239
Josh Gaofec44372017-08-28 13:22:55 -0700240 case RebootType::shutdown:
Paul Lawrence87999172014-02-20 12:21:31 -0800241 property_set(ANDROID_RB_PROPERTY, "shutdown");
242 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700243 }
Paul Lawrence87999172014-02-20 12:21:31 -0800244
Ken Sumralladfba362013-06-04 16:37:52 -0700245 sleep(20);
246
247 /* Shouldn't get here, reboot should happen before sleep times out */
248 return;
249}
250
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800251static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
252{
253 memset(io, 0, dataSize);
254 io->data_size = dataSize;
255 io->data_start = sizeof(struct dm_ioctl);
256 io->version[0] = 4;
257 io->version[1] = 0;
258 io->version[2] = 0;
259 io->flags = flags;
260 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100261 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800262 }
263}
264
Greg Kaiser38723f22018-02-16 13:35:35 -0800265namespace {
266
267struct CryptoType;
268
269// Use to get the CryptoType in use on this device.
270const CryptoType &get_crypto_type();
271
272struct CryptoType {
273 // We should only be constructing CryptoTypes as part of
274 // supported_crypto_types[]. We do it via this pseudo-builder pattern,
275 // which isn't pure or fully protected as a concession to being able to
276 // do it all at compile time. Add new CryptoTypes in
277 // supported_crypto_types[] below.
278 constexpr CryptoType() : CryptoType(nullptr, nullptr, 0xFFFFFFFF) {}
279 constexpr CryptoType set_keysize(uint32_t size) const {
280 return CryptoType(this->property_name, this->crypto_name, size);
281 }
282 constexpr CryptoType set_property_name(const char *property) const {
283 return CryptoType(property, this->crypto_name, this->keysize);
284 }
285 constexpr CryptoType set_crypto_name(const char *crypto) const {
286 return CryptoType(this->property_name, crypto, this->keysize);
287 }
288
289 constexpr const char *get_property_name() const { return property_name; }
290 constexpr const char *get_crypto_name() const { return crypto_name; }
291 constexpr uint32_t get_keysize() const { return keysize; }
292
293 private:
294 const char *property_name;
295 const char *crypto_name;
296 uint32_t keysize;
297
298 constexpr CryptoType(const char *property, const char *crypto,
299 uint32_t ksize)
300 : property_name(property), crypto_name(crypto), keysize(ksize) {}
301 friend const CryptoType &get_crypto_type();
302 static const CryptoType &get_device_crypto_algorithm();
303};
304
305// We only want to parse this read-only property once. But we need to wait
306// until the system is initialized before we can read it. So we use a static
307// scoped within this function to get it only once.
308const CryptoType &get_crypto_type() {
309 static CryptoType crypto_type = CryptoType::get_device_crypto_algorithm();
310 return crypto_type;
311}
312
313constexpr CryptoType default_crypto_type = CryptoType()
314 .set_property_name("AES-128-CBC")
315 .set_crypto_name("aes-cbc-essiv:sha256")
316 .set_keysize(16);
317
318constexpr CryptoType supported_crypto_types[] = {
319 default_crypto_type,
Greg Kaiser38723f22018-02-16 13:35:35 -0800320 // Add new CryptoTypes here. Order is not important.
321};
322
323
324// ---------- START COMPILE-TIME SANITY CHECK BLOCK -------------------------
325// We confirm all supported_crypto_types have a small enough keysize and
326// had both set_property_name() and set_crypto_name() called.
327
328template <typename T, size_t N>
329constexpr size_t array_length(T (&)[N]) { return N; }
330
331constexpr bool indexOutOfBoundsForCryptoTypes(size_t index) {
332 return (index >= array_length(supported_crypto_types));
333}
334
335constexpr bool isValidCryptoType(const CryptoType &crypto_type) {
336 return ((crypto_type.get_property_name() != nullptr) &&
337 (crypto_type.get_crypto_name() != nullptr) &&
338 (crypto_type.get_keysize() <= MAX_KEY_LEN));
339}
340
341// Note in C++11 that constexpr functions can only have a single line.
342// So our code is a bit convoluted (using recursion instead of a loop),
343// but it's asserting at compile time that all of our key lengths are valid.
344constexpr bool validateSupportedCryptoTypes(size_t index) {
345 return indexOutOfBoundsForCryptoTypes(index) ||
346 (isValidCryptoType(supported_crypto_types[index]) &&
347 validateSupportedCryptoTypes(index + 1));
348}
349
350static_assert(validateSupportedCryptoTypes(0),
351 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
352 "incompletely constructed.");
353// ---------- END COMPILE-TIME SANITY CHECK BLOCK -------------------------
354
355
356// Don't call this directly, use get_crypto_type(), which caches this result.
357const CryptoType &CryptoType::get_device_crypto_algorithm() {
358 constexpr char CRYPT_ALGO_PROP[] = "ro.crypto.fde_algorithm";
359 char paramstr[PROPERTY_VALUE_MAX];
360
361 property_get(CRYPT_ALGO_PROP, paramstr,
362 default_crypto_type.get_property_name());
363 for (auto const &ctype : supported_crypto_types) {
364 if (strcmp(paramstr, ctype.get_property_name()) == 0) {
365 return ctype;
366 }
367 }
368 ALOGE("Invalid name (%s) for %s. Defaulting to %s\n", paramstr,
369 CRYPT_ALGO_PROP, default_crypto_type.get_property_name());
370 return default_crypto_type;
371}
372
373} // namespace
374
375
376
Kenny Rootc4c70f12013-06-14 12:11:38 -0700377/**
378 * Gets the default device scrypt parameters for key derivation time tuning.
379 * The parameters should lead to about one second derivation time for the
380 * given device.
381 */
382static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700383 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000384 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700385
Paul Crowley63c18d32016-02-10 14:02:47 +0000386 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
387 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
388 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
389 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700390 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000391 ftr->N_factor = Nf;
392 ftr->r_factor = rf;
393 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700394}
395
Greg Kaiser57f9af62018-02-16 13:13:58 -0800396uint32_t cryptfs_get_keysize() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800397 return get_crypto_type().get_keysize();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800398}
399
400const char *cryptfs_get_crypto_name() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800401 return get_crypto_type().get_crypto_name();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800402}
403
Ken Sumrall3ed82362011-01-28 23:31:16 -0800404static unsigned int get_fs_size(char *dev)
405{
406 int fd, block_size;
407 struct ext4_super_block sb;
408 off64_t len;
409
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700410 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800411 SLOGE("Cannot open device to get filesystem size ");
412 return 0;
413 }
414
415 if (lseek64(fd, 1024, SEEK_SET) < 0) {
416 SLOGE("Cannot seek to superblock");
417 return 0;
418 }
419
420 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
421 SLOGE("Cannot read superblock");
422 return 0;
423 }
424
425 close(fd);
426
Daniel Rosenberge82df162014-08-15 22:19:23 +0000427 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
428 SLOGE("Not a valid ext4 superblock");
429 return 0;
430 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800431 block_size = 1024 << sb.s_log_block_size;
432 /* compute length in bytes */
433 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
434
435 /* return length in sectors */
436 return (unsigned int) (len / 512);
437}
438
Ken Sumrall160b4d62013-04-22 12:15:39 -0700439static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
440{
441 static int cached_data = 0;
442 static off64_t cached_off = 0;
443 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
444 int fd;
445 char key_loc[PROPERTY_VALUE_MAX];
446 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700447 int rc = -1;
448
449 if (!cached_data) {
Paul Crowleye2ee1522017-09-26 14:05:26 -0700450 fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700451
452 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700453 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700454 SLOGE("Cannot open real block device %s\n", real_blkdev);
455 return -1;
456 }
457
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900458 unsigned long nr_sec = 0;
459 get_blkdev_size(fd, &nr_sec);
460 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700461 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
462 * encryption info footer and key, and plenty of bytes to spare for future
463 * growth.
464 */
465 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
466 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
467 cached_data = 1;
468 } else {
469 SLOGE("Cannot get size of block device %s\n", real_blkdev);
470 }
471 close(fd);
472 } else {
473 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
474 cached_off = 0;
475 cached_data = 1;
476 }
477 }
478
479 if (cached_data) {
480 if (metadata_fname) {
481 *metadata_fname = cached_metadata_fname;
482 }
483 if (off) {
484 *off = cached_off;
485 }
486 rc = 0;
487 }
488
489 return rc;
490}
491
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800492/* Set sha256 checksum in structure */
493static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr)
494{
495 SHA256_CTX c;
496 SHA256_Init(&c);
497 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
498 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
499 SHA256_Final(crypt_ftr->sha256, &c);
500}
501
Ken Sumralle8744072011-01-18 22:01:55 -0800502/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800503 * update the failed mount count but not change the key.
504 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700505static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800506{
507 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800508 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700509 /* starting_off is set to the SEEK_SET offset
510 * where the crypto structure starts
511 */
512 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800513 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700514 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700515 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800516
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800517 set_ftr_sha(crypt_ftr);
518
Ken Sumrall160b4d62013-04-22 12:15:39 -0700519 if (get_crypt_ftr_info(&fname, &starting_off)) {
520 SLOGE("Unable to get crypt_ftr_info\n");
521 return -1;
522 }
523 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700524 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700525 return -1;
526 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700527 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700528 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700529 return -1;
530 }
531
532 /* Seek to the start of the crypt footer */
533 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
534 SLOGE("Cannot seek to real block device footer\n");
535 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800536 }
537
538 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
539 SLOGE("Cannot write real block device footer\n");
540 goto errout;
541 }
542
Ken Sumrall3be890f2011-09-14 16:53:46 -0700543 fstat(fd, &statbuf);
544 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700545 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700546 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800547 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800548 goto errout;
549 }
550 }
551
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800552 /* Success! */
553 rc = 0;
554
555errout:
556 close(fd);
557 return rc;
558
559}
560
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800561static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr)
562{
563 struct crypt_mnt_ftr copy;
564 memcpy(&copy, crypt_ftr, sizeof(copy));
565 set_ftr_sha(&copy);
566 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
567}
568
Ken Sumrall160b4d62013-04-22 12:15:39 -0700569static inline int unix_read(int fd, void* buff, int len)
570{
571 return TEMP_FAILURE_RETRY(read(fd, buff, len));
572}
573
574static inline int unix_write(int fd, const void* buff, int len)
575{
576 return TEMP_FAILURE_RETRY(write(fd, buff, len));
577}
578
579static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
580{
581 memset(pdata, 0, len);
582 pdata->persist_magic = PERSIST_DATA_MAGIC;
583 pdata->persist_valid_entries = 0;
584}
585
586/* A routine to update the passed in crypt_ftr to the lastest version.
587 * fd is open read/write on the device that holds the crypto footer and persistent
588 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
589 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
590 */
591static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
592{
Kenny Root7434b312013-06-14 11:29:53 -0700593 int orig_major = crypt_ftr->major_version;
594 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700595
Kenny Root7434b312013-06-14 11:29:53 -0700596 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
597 struct crypt_persist_data *pdata;
598 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700599
Kenny Rootc4c70f12013-06-14 12:11:38 -0700600 SLOGW("upgrading crypto footer to 1.1");
601
Wei Wang4375f1b2017-02-24 17:43:01 -0800602 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700603 if (pdata == NULL) {
604 SLOGE("Cannot allocate persisent data\n");
605 return;
606 }
607 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
608
609 /* Need to initialize the persistent data area */
610 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
611 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100612 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700613 return;
614 }
615 /* Write all zeros to the first copy, making it invalid */
616 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
617
618 /* Write a valid but empty structure to the second copy */
619 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
620 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
621
622 /* Update the footer */
623 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
624 crypt_ftr->persist_data_offset[0] = pdata_offset;
625 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
626 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100627 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700628 }
629
Paul Lawrencef4faa572014-01-29 13:31:03 -0800630 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700631 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800632 /* But keep the old kdf_type.
633 * It will get updated later to KDF_SCRYPT after the password has been verified.
634 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700635 crypt_ftr->kdf_type = KDF_PBKDF2;
636 get_device_scrypt_params(crypt_ftr);
637 crypt_ftr->minor_version = 2;
638 }
639
Paul Lawrencef4faa572014-01-29 13:31:03 -0800640 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
641 SLOGW("upgrading crypto footer to 1.3");
642 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
643 crypt_ftr->minor_version = 3;
644 }
645
Kenny Root7434b312013-06-14 11:29:53 -0700646 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
647 if (lseek64(fd, offset, SEEK_SET) == -1) {
648 SLOGE("Cannot seek to crypt footer\n");
649 return;
650 }
651 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700652 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700653}
654
655
656static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800657{
658 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800659 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700660 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800661 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700662 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700663 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800664
Ken Sumrall160b4d62013-04-22 12:15:39 -0700665 if (get_crypt_ftr_info(&fname, &starting_off)) {
666 SLOGE("Unable to get crypt_ftr_info\n");
667 return -1;
668 }
669 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700670 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700671 return -1;
672 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700673 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700674 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700675 return -1;
676 }
677
678 /* Make sure it's 16 Kbytes in length */
679 fstat(fd, &statbuf);
680 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
681 SLOGE("footer file %s is not the expected size!\n", fname);
682 goto errout;
683 }
684
685 /* Seek to the start of the crypt footer */
686 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
687 SLOGE("Cannot seek to real block device footer\n");
688 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800689 }
690
691 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
692 SLOGE("Cannot read real block device footer\n");
693 goto errout;
694 }
695
696 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700697 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800698 goto errout;
699 }
700
Kenny Rootc96a5f82013-06-14 12:08:28 -0700701 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
702 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
703 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800704 goto errout;
705 }
706
Greg Kaiser59ad0182018-02-16 13:01:36 -0800707 // We risk buffer overflows with oversized keys, so we just reject them.
708 // 0-sized keys are problematic (essentially by-passing encryption), and
709 // AES-CBC key wrapping only works for multiples of 16 bytes.
710 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
711 (crypt_ftr->keysize > MAX_KEY_LEN)) {
712 SLOGE("Invalid keysize (%u) for block device %s; Must be non-zero, "
713 "divisible by 16, and <= %d\n", crypt_ftr->keysize, fname,
714 MAX_KEY_LEN);
715 goto errout;
716 }
717
Kenny Rootc96a5f82013-06-14 12:08:28 -0700718 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
719 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
720 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800721 }
722
Ken Sumrall160b4d62013-04-22 12:15:39 -0700723 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
724 * copy on disk before returning.
725 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700726 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700727 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800728 }
729
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800730 /* Success! */
731 rc = 0;
732
733errout:
734 close(fd);
735 return rc;
736}
737
Ken Sumrall160b4d62013-04-22 12:15:39 -0700738static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
739{
740 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
741 crypt_ftr->persist_data_offset[1]) {
742 SLOGE("Crypt_ftr persist data regions overlap");
743 return -1;
744 }
745
746 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
747 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
748 return -1;
749 }
750
751 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
752 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
753 CRYPT_FOOTER_OFFSET) {
754 SLOGE("Persistent data extends past crypto footer");
755 return -1;
756 }
757
758 return 0;
759}
760
761static int load_persistent_data(void)
762{
763 struct crypt_mnt_ftr crypt_ftr;
764 struct crypt_persist_data *pdata = NULL;
765 char encrypted_state[PROPERTY_VALUE_MAX];
766 char *fname;
767 int found = 0;
768 int fd;
769 int ret;
770 int i;
771
772 if (persist_data) {
773 /* Nothing to do, we've already loaded or initialized it */
774 return 0;
775 }
776
777
778 /* If not encrypted, just allocate an empty table and initialize it */
779 property_get("ro.crypto.state", encrypted_state, "");
780 if (strcmp(encrypted_state, "encrypted") ) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800781 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700782 if (pdata) {
783 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
784 persist_data = pdata;
785 return 0;
786 }
787 return -1;
788 }
789
790 if(get_crypt_ftr_and_key(&crypt_ftr)) {
791 return -1;
792 }
793
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700794 if ((crypt_ftr.major_version < 1)
795 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700796 SLOGE("Crypt_ftr version doesn't support persistent data");
797 return -1;
798 }
799
800 if (get_crypt_ftr_info(&fname, NULL)) {
801 return -1;
802 }
803
804 ret = validate_persistent_data_storage(&crypt_ftr);
805 if (ret) {
806 return -1;
807 }
808
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700809 fd = open(fname, O_RDONLY|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700810 if (fd < 0) {
811 SLOGE("Cannot open %s metadata file", fname);
812 return -1;
813 }
814
Wei Wang4375f1b2017-02-24 17:43:01 -0800815 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800816 if (pdata == NULL) {
817 SLOGE("Cannot allocate memory for persistent data");
818 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700819 }
820
821 for (i = 0; i < 2; i++) {
822 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
823 SLOGE("Cannot seek to read persistent data on %s", fname);
824 goto err2;
825 }
826 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
827 SLOGE("Error reading persistent data on iteration %d", i);
828 goto err2;
829 }
830 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
831 found = 1;
832 break;
833 }
834 }
835
836 if (!found) {
837 SLOGI("Could not find valid persistent data, creating");
838 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
839 }
840
841 /* Success */
842 persist_data = pdata;
843 close(fd);
844 return 0;
845
846err2:
847 free(pdata);
848
849err:
850 close(fd);
851 return -1;
852}
853
854static int save_persistent_data(void)
855{
856 struct crypt_mnt_ftr crypt_ftr;
857 struct crypt_persist_data *pdata;
858 char *fname;
859 off64_t write_offset;
860 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700861 int fd;
862 int ret;
863
864 if (persist_data == NULL) {
865 SLOGE("No persistent data to save");
866 return -1;
867 }
868
869 if(get_crypt_ftr_and_key(&crypt_ftr)) {
870 return -1;
871 }
872
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700873 if ((crypt_ftr.major_version < 1)
874 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700875 SLOGE("Crypt_ftr version doesn't support persistent data");
876 return -1;
877 }
878
879 ret = validate_persistent_data_storage(&crypt_ftr);
880 if (ret) {
881 return -1;
882 }
883
884 if (get_crypt_ftr_info(&fname, NULL)) {
885 return -1;
886 }
887
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700888 fd = open(fname, O_RDWR|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700889 if (fd < 0) {
890 SLOGE("Cannot open %s metadata file", fname);
891 return -1;
892 }
893
Wei Wang4375f1b2017-02-24 17:43:01 -0800894 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700895 if (pdata == NULL) {
896 SLOGE("Cannot allocate persistant data");
897 goto err;
898 }
899
900 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
901 SLOGE("Cannot seek to read persistent data on %s", fname);
902 goto err2;
903 }
904
905 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
906 SLOGE("Error reading persistent data before save");
907 goto err2;
908 }
909
910 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
911 /* The first copy is the curent valid copy, so write to
912 * the second copy and erase this one */
913 write_offset = crypt_ftr.persist_data_offset[1];
914 erase_offset = crypt_ftr.persist_data_offset[0];
915 } else {
916 /* The second copy must be the valid copy, so write to
917 * the first copy, and erase the second */
918 write_offset = crypt_ftr.persist_data_offset[0];
919 erase_offset = crypt_ftr.persist_data_offset[1];
920 }
921
922 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100923 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700924 SLOGE("Cannot seek to write persistent data");
925 goto err2;
926 }
927 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
928 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100929 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700930 SLOGE("Cannot seek to erase previous persistent data");
931 goto err2;
932 }
933 fsync(fd);
934 memset(pdata, 0, crypt_ftr.persist_data_size);
935 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
936 (int) crypt_ftr.persist_data_size) {
937 SLOGE("Cannot write to erase previous persistent data");
938 goto err2;
939 }
940 fsync(fd);
941 } else {
942 SLOGE("Cannot write to save persistent data");
943 goto err2;
944 }
945
946 /* Success */
947 free(pdata);
948 close(fd);
949 return 0;
950
951err2:
952 free(pdata);
953err:
954 close(fd);
955 return -1;
956}
957
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800958/* Convert a binary key of specified length into an ascii hex string equivalent,
959 * without the leading 0x and with null termination
960 */
Jeff Sharkey9c484982015-03-31 10:35:33 -0700961static void convert_key_to_hex_ascii(const unsigned char *master_key,
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700962 unsigned int keysize, char *master_key_ascii) {
963 unsigned int i, a;
964 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800965
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700966 for (i=0, a=0; i<keysize; i++, a+=2) {
967 /* For each byte, write out two ascii hex digits */
968 nibble = (master_key[i] >> 4) & 0xf;
969 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800970
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700971 nibble = master_key[i] & 0xf;
972 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
973 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800974
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700975 /* Add the null termination */
976 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800977
978}
979
Jeff Sharkey9c484982015-03-31 10:35:33 -0700980static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
981 const unsigned char *master_key, const char *real_blk_name,
982 const char *name, int fd, const char *extra_params) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800983 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800984 struct dm_ioctl *io;
985 struct dm_target_spec *tgt;
986 char *crypt_params;
Greg Kaiser59ad0182018-02-16 13:01:36 -0800987 // We need two ASCII characters to represent each byte, and need space for
988 // the '\0' terminator.
989 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
George Burgess IV605d7ae2016-02-29 13:39:17 -0800990 size_t buff_offset;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800991 int i;
992
993 io = (struct dm_ioctl *) buffer;
994
995 /* Load the mapping table for this device */
996 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
997
998 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
999 io->target_count = 1;
1000 tgt->status = 0;
1001 tgt->sector_start = 0;
1002 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -07001003 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Ken Sumralldb5e0262013-02-05 17:39:48 -08001004
1005 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
1006 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
George Burgess IV605d7ae2016-02-29 13:39:17 -08001007
1008 buff_offset = crypt_params - buffer;
Paul Crowley5afbc622017-11-27 09:42:17 -08001009 SLOGI("Extra parameters for dm_crypt: %s\n", extra_params);
George Burgess IV605d7ae2016-02-29 13:39:17 -08001010 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
1011 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name,
1012 extra_params);
Ken Sumralldb5e0262013-02-05 17:39:48 -08001013 crypt_params += strlen(crypt_params) + 1;
1014 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1015 tgt->next = crypt_params - buffer;
1016
1017 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1018 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
1019 break;
1020 }
1021 usleep(500000);
1022 }
1023
1024 if (i == TABLE_LOAD_RETRIES) {
1025 /* We failed to load the table, return an error */
1026 return -1;
1027 } else {
1028 return i + 1;
1029 }
1030}
1031
1032
1033static int get_dm_crypt_version(int fd, const char *name, int *version)
1034{
1035 char buffer[DM_CRYPT_BUF_SIZE];
1036 struct dm_ioctl *io;
1037 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001038
1039 io = (struct dm_ioctl *) buffer;
1040
1041 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1042
1043 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1044 return -1;
1045 }
1046
1047 /* Iterate over the returned versions, looking for name of "crypt".
1048 * When found, get and return the version.
1049 */
1050 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1051 while (v->next) {
1052 if (! strcmp(v->name, "crypt")) {
1053 /* We found the crypt driver, return the version, and get out */
1054 version[0] = v->version[0];
1055 version[1] = v->version[1];
1056 version[2] = v->version[2];
1057 return 0;
1058 }
1059 v = (struct dm_target_versions *)(((char *)v) + v->next);
1060 }
1061
1062 return -1;
1063}
1064
Paul Crowley5afbc622017-11-27 09:42:17 -08001065static std::string extra_params_as_string(const std::vector<std::string>& extra_params_vec) {
1066 if (extra_params_vec.empty()) return "";
1067 std::string extra_params = std::to_string(extra_params_vec.size());
1068 for (const auto& p : extra_params_vec) {
1069 extra_params.append(" ");
1070 extra_params.append(p);
1071 }
1072 return extra_params;
1073}
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001074
Paul Crowley5afbc622017-11-27 09:42:17 -08001075static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
1076 const char* real_blk_name, char* crypto_blk_name, const char* name,
1077 uint32_t flags) {
1078 char buffer[DM_CRYPT_BUF_SIZE];
1079 struct dm_ioctl* io;
1080 unsigned int minor;
1081 int fd = 0;
1082 int err;
1083 int retval = -1;
1084 int version[3];
1085 int load_count;
1086 std::vector<std::string> extra_params_vec;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001087
Paul Crowley5afbc622017-11-27 09:42:17 -08001088 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1089 SLOGE("Cannot open device-mapper\n");
1090 goto errout;
1091 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001092
Paul Crowley5afbc622017-11-27 09:42:17 -08001093 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001094
Paul Crowley5afbc622017-11-27 09:42:17 -08001095 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1096 err = ioctl(fd, DM_DEV_CREATE, io);
1097 if (err) {
1098 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
1099 goto errout;
1100 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001101
Paul Crowley5afbc622017-11-27 09:42:17 -08001102 /* Get the device status, in particular, the name of it's device file */
1103 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1104 if (ioctl(fd, DM_DEV_STATUS, io)) {
1105 SLOGE("Cannot retrieve dm-crypt device status\n");
1106 goto errout;
1107 }
1108 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1109 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
Ken Sumralle919efe2012-09-29 17:07:41 -07001110
Paul Crowley5afbc622017-11-27 09:42:17 -08001111 if (!get_dm_crypt_version(fd, name, version)) {
1112 /* Support for allow_discards was added in version 1.11.0 */
1113 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
1114 extra_params_vec.emplace_back("allow_discards");
1115 }
1116 }
1117 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
1118 extra_params_vec.emplace_back("allow_encrypt_override");
1119 }
1120 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1121 extra_params_as_string(extra_params_vec).c_str());
1122 if (load_count < 0) {
1123 SLOGE("Cannot load dm-crypt mapping table.\n");
1124 goto errout;
1125 } else if (load_count > 1) {
1126 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1127 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001128
Paul Crowley5afbc622017-11-27 09:42:17 -08001129 /* Resume this device to activate it */
1130 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001131
Paul Crowley5afbc622017-11-27 09:42:17 -08001132 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1133 SLOGE("Cannot resume the dm-crypt device\n");
1134 goto errout;
1135 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001136
Paul Crowley5afbc622017-11-27 09:42:17 -08001137 /* We made it here with no errors. Woot! */
1138 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001139
1140errout:
1141 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1142
1143 return retval;
1144}
1145
Wei Wang4375f1b2017-02-24 17:43:01 -08001146static int delete_crypto_blk_dev(const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001147{
1148 int fd;
1149 char buffer[DM_CRYPT_BUF_SIZE];
1150 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001151 int retval = -1;
1152
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001153 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001154 SLOGE("Cannot open device-mapper\n");
1155 goto errout;
1156 }
1157
1158 io = (struct dm_ioctl *) buffer;
1159
1160 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1161 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1162 SLOGE("Cannot remove dm-crypt device\n");
1163 goto errout;
1164 }
1165
1166 /* We made it here with no errors. Woot! */
1167 retval = 0;
1168
1169errout:
1170 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1171
1172 return retval;
1173
1174}
1175
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001176static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001177 unsigned char *ikey, void *params UNUSED)
1178{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001179 SLOGI("Using pbkdf2 for cryptfs KDF");
1180
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001181 /* Turn the password into a key and IV that can decrypt the master key */
Adam Langleybf0d9722015-11-04 14:51:39 -08001182 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001183 HASH_COUNT, INTERMEDIATE_BUF_SIZE,
Adam Langleybf0d9722015-11-04 14:51:39 -08001184 ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001185}
1186
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001187static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001188 unsigned char *ikey, void *params)
1189{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001190 SLOGI("Using scrypt for cryptfs KDF");
1191
Kenny Rootc4c70f12013-06-14 12:11:38 -07001192 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1193
1194 int N = 1 << ftr->N_factor;
1195 int r = 1 << ftr->r_factor;
1196 int p = 1 << ftr->p_factor;
1197
1198 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001199 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1200 salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001201 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001202
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001203 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001204}
1205
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001206static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1207 unsigned char *ikey, void *params)
1208{
1209 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1210
1211 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001212 size_t signature_size;
1213 unsigned char* signature;
1214 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1215
1216 int N = 1 << ftr->N_factor;
1217 int r = 1 << ftr->r_factor;
1218 int p = 1 << ftr->p_factor;
1219
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001220 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1221 salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001222 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001223
1224 if (rc) {
1225 SLOGE("scrypt failed");
1226 return -1;
1227 }
1228
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001229 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE,
Shawn Willdene17a9c42014-09-08 13:04:08 -06001230 &signature, &signature_size)) {
1231 SLOGE("Signing failed");
1232 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001233 }
1234
1235 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001236 N, r, p, ikey, INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001237 free(signature);
1238
1239 if (rc) {
1240 SLOGE("scrypt failed");
1241 return -1;
1242 }
1243
1244 return 0;
1245}
1246
1247static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1248 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001249 unsigned char *encrypted_master_key,
1250 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001251{
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001252 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = { 0 };
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001253 EVP_CIPHER_CTX e_ctx;
1254 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001255 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001256
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001257 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001258 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001259
1260 switch (crypt_ftr->kdf_type) {
1261 case KDF_SCRYPT_KEYMASTER:
1262 if (keymaster_create_key(crypt_ftr)) {
1263 SLOGE("keymaster_create_key failed");
1264 return -1;
1265 }
1266
1267 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1268 SLOGE("scrypt failed");
1269 return -1;
1270 }
1271 break;
1272
1273 case KDF_SCRYPT:
1274 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1275 SLOGE("scrypt failed");
1276 return -1;
1277 }
1278 break;
1279
1280 default:
1281 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001282 return -1;
1283 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001284
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001285 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001286 EVP_CIPHER_CTX_init(&e_ctx);
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001287 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1288 ikey+INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001289 SLOGE("EVP_EncryptInit failed\n");
1290 return -1;
1291 }
1292 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001293
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001294 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001295 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Greg Kaiser59ad0182018-02-16 13:01:36 -08001296 decrypted_master_key, crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001297 SLOGE("EVP_EncryptUpdate failed\n");
1298 return -1;
1299 }
Adam Langley889c4f12014-09-03 14:23:13 -07001300 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001301 SLOGE("EVP_EncryptFinal failed\n");
1302 return -1;
1303 }
1304
Greg Kaiser59ad0182018-02-16 13:01:36 -08001305 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001306 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1307 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001308 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001309
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001310 /* Store the scrypt of the intermediate key, so we can validate if it's a
1311 password error or mount error when things go wrong.
1312 Note there's no need to check for errors, since if this is incorrect, we
1313 simply won't wipe userdata, which is the correct default behavior
1314 */
1315 int N = 1 << crypt_ftr->N_factor;
1316 int r = 1 << crypt_ftr->r_factor;
1317 int p = 1 << crypt_ftr->p_factor;
1318
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001319 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001320 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1321 crypt_ftr->scrypted_intermediate_key,
1322 sizeof(crypt_ftr->scrypted_intermediate_key));
1323
1324 if (rc) {
1325 SLOGE("encrypt_master_key: crypto_scrypt failed");
1326 }
1327
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001328 EVP_CIPHER_CTX_cleanup(&e_ctx);
1329
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001330 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001331}
1332
Paul Lawrence731a7a22015-04-28 22:14:15 +00001333static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Greg Kaiser59ad0182018-02-16 13:01:36 -08001334 const unsigned char *encrypted_master_key,
1335 size_t keysize,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001336 unsigned char *decrypted_master_key,
1337 kdf_func kdf, void *kdf_params,
1338 unsigned char** intermediate_key,
1339 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001340{
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001341 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = { 0 };
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001342 EVP_CIPHER_CTX d_ctx;
1343 int decrypted_len, final_len;
1344
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001345 /* Turn the password into an intermediate key and IV that can decrypt the
1346 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001347 if (kdf(passwd, salt, ikey, kdf_params)) {
1348 SLOGE("kdf failed");
1349 return -1;
1350 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001351
1352 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001353 EVP_CIPHER_CTX_init(&d_ctx);
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001354 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001355 return -1;
1356 }
1357 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1358 /* Decrypt the master key */
1359 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
Greg Kaiser59ad0182018-02-16 13:01:36 -08001360 encrypted_master_key, keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001361 return -1;
1362 }
Adam Langley889c4f12014-09-03 14:23:13 -07001363 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001364 return -1;
1365 }
1366
Greg Kaiser59ad0182018-02-16 13:01:36 -08001367 if (decrypted_len + final_len != static_cast<int>(keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001368 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001369 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001370
1371 /* Copy intermediate key if needed by params */
1372 if (intermediate_key && intermediate_key_size) {
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001373 *intermediate_key = (unsigned char*) malloc(INTERMEDIATE_KEY_LEN_BYTES);
Greg Kaisere8167af2016-04-20 10:50:15 -07001374 if (*intermediate_key) {
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001375 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1376 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001377 }
1378 }
1379
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001380 EVP_CIPHER_CTX_cleanup(&d_ctx);
1381
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001382 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001383}
1384
Kenny Rootc4c70f12013-06-14 12:11:38 -07001385static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001386{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001387 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001388 *kdf = scrypt_keymaster;
1389 *kdf_params = ftr;
1390 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001391 *kdf = scrypt;
1392 *kdf_params = ftr;
1393 } else {
1394 *kdf = pbkdf2;
1395 *kdf_params = NULL;
1396 }
1397}
1398
Paul Lawrence731a7a22015-04-28 22:14:15 +00001399static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001400 struct crypt_mnt_ftr *crypt_ftr,
1401 unsigned char** intermediate_key,
1402 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001403{
1404 kdf_func kdf;
1405 void *kdf_params;
1406 int ret;
1407
1408 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001409 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
Greg Kaiser59ad0182018-02-16 13:01:36 -08001410 crypt_ftr->keysize,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001411 decrypted_master_key, kdf, kdf_params,
1412 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001413 if (ret != 0) {
1414 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001415 }
1416
1417 return ret;
1418}
1419
Wei Wang4375f1b2017-02-24 17:43:01 -08001420static int create_encrypted_random_key(const char *passwd, unsigned char *master_key, unsigned char *salt,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001421 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001422 int fd;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001423 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001424
1425 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001426 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001427 read(fd, key_buf, sizeof(key_buf));
1428 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001429 close(fd);
1430
1431 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001432 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001433}
1434
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001435int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001436{
Greg Hackmann955653e2014-09-24 14:55:20 -07001437 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001438#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001439
1440 /* Now umount the tmpfs filesystem */
1441 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001442 if (umount(mountpoint) == 0) {
1443 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001444 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001445
1446 if (errno == EINVAL) {
1447 /* EINVAL is returned if the directory is not a mountpoint,
1448 * i.e. there is no filesystem mounted there. So just get out.
1449 */
1450 break;
1451 }
1452
1453 err = errno;
1454
1455 /* If allowed, be increasingly aggressive before the last two retries */
1456 if (kill) {
1457 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1458 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001459 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001460 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1461 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001462 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001463 }
1464 }
1465
1466 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001467 }
1468
1469 if (i < WAIT_UNMOUNT_COUNT) {
1470 SLOGD("unmounting %s succeeded\n", mountpoint);
1471 rc = 0;
1472 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001473 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001474 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001475 rc = -1;
1476 }
1477
1478 return rc;
1479}
1480
Wei Wang42e38102017-06-07 10:46:12 -07001481static void prep_data_fs(void)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001482{
Jeff Sharkey47695b22016-02-01 17:02:29 -07001483 // NOTE: post_fs_data results in init calling back around to vold, so all
1484 // callers to this method must be async
1485
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001486 /* Do the prep of the /data filesystem */
1487 property_set("vold.post_fs_data_done", "0");
1488 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001489 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001490
Ken Sumrallc5872692013-05-14 15:26:31 -07001491 /* Wait a max of 50 seconds, hopefully it takes much less */
Wei Wang42e38102017-06-07 10:46:12 -07001492 while (!android::base::WaitForProperty("vold.post_fs_data_done",
Wei Wang4375f1b2017-02-24 17:43:01 -08001493 "1",
Wei Wang42e38102017-06-07 10:46:12 -07001494 std::chrono::seconds(15))) {
1495 /* We timed out to prep /data in time. Continue wait. */
1496 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001497 }
Wei Wang42e38102017-06-07 10:46:12 -07001498 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001499}
1500
Paul Lawrence74f29f12014-08-28 15:54:10 -07001501static void cryptfs_set_corrupt()
1502{
1503 // Mark the footer as bad
1504 struct crypt_mnt_ftr crypt_ftr;
1505 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1506 SLOGE("Failed to get crypto footer - panic");
1507 return;
1508 }
1509
1510 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1511 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1512 SLOGE("Failed to set crypto footer - panic");
1513 return;
1514 }
1515}
1516
1517static void cryptfs_trigger_restart_min_framework()
1518{
1519 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1520 SLOGE("Failed to mount tmpfs on data - panic");
1521 return;
1522 }
1523
1524 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1525 SLOGE("Failed to trigger post fs data - panic");
1526 return;
1527 }
1528
1529 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1530 SLOGE("Failed to trigger restart min framework - panic");
1531 return;
1532 }
1533}
1534
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001535/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001536static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001537{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001538 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001539 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001540 static int restart_successful = 0;
1541
1542 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001543 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001544 SLOGE("Encrypted filesystem not validated, aborting");
1545 return -1;
1546 }
1547
1548 if (restart_successful) {
1549 SLOGE("System already restarted with encrypted disk, aborting");
1550 return -1;
1551 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001552
Paul Lawrencef4faa572014-01-29 13:31:03 -08001553 if (restart_main) {
1554 /* Here is where we shut down the framework. The init scripts
1555 * start all services in one of three classes: core, main or late_start.
1556 * On boot, we start core and main. Now, we stop main, but not core,
1557 * as core includes vold and a few other really important things that
1558 * we need to keep running. Once main has stopped, we should be able
1559 * to umount the tmpfs /data, then mount the encrypted /data.
1560 * We then restart the class main, and also the class late_start.
1561 * At the moment, I've only put a few things in late_start that I know
1562 * are not needed to bring up the framework, and that also cause problems
1563 * with unmounting the tmpfs /data, but I hope to add add more services
1564 * to the late_start class as we optimize this to decrease the delay
1565 * till the user is asked for the password to the filesystem.
1566 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001567
Paul Lawrencef4faa572014-01-29 13:31:03 -08001568 /* The init files are setup to stop the class main when vold.decrypt is
1569 * set to trigger_reset_main.
1570 */
1571 property_set("vold.decrypt", "trigger_reset_main");
1572 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001573
Paul Lawrencef4faa572014-01-29 13:31:03 -08001574 /* Ugh, shutting down the framework is not synchronous, so until it
1575 * can be fixed, this horrible hack will wait a moment for it all to
1576 * shut down before proceeding. Without it, some devices cannot
1577 * restart the graphics services.
1578 */
1579 sleep(2);
1580 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001581
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001582 /* Now that the framework is shutdown, we should be able to umount()
1583 * the tmpfs filesystem, and mount the real one.
1584 */
1585
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001586 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1587 if (strlen(crypto_blkdev) == 0) {
1588 SLOGE("fs_crypto_blkdev not set\n");
1589 return -1;
1590 }
1591
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001592 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001593 /* If ro.crypto.readonly is set to 1, mount the decrypted
1594 * filesystem readonly. This is used when /data is mounted by
1595 * recovery mode.
1596 */
1597 char ro_prop[PROPERTY_VALUE_MAX];
1598 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001599 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001600 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Doug Zongker6fd57712013-12-17 09:43:23 -08001601 rec->flags |= MS_RDONLY;
1602 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001603
Ken Sumralle5032c42012-04-01 23:58:44 -07001604 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001605 int retries = RETRY_MOUNT_ATTEMPTS;
1606 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001607
1608 /*
1609 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1610 * partitions in the fsck domain.
1611 */
1612 if (setexeccon(secontextFsck())){
1613 SLOGE("Failed to setexeccon");
1614 return -1;
1615 }
Paul Crowleye2ee1522017-09-26 14:05:26 -07001616 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT,
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001617 crypto_blkdev, 0))
1618 != 0) {
1619 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1620 /* TODO: invoke something similar to
1621 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1622 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1623 SLOGI("Failed to mount %s because it is busy - waiting",
1624 crypto_blkdev);
1625 if (--retries) {
1626 sleep(RETRY_MOUNT_DELAY_SECONDS);
1627 } else {
1628 /* Let's hope that a reboot clears away whatever is keeping
1629 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001630 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001631 }
1632 } else {
1633 SLOGE("Failed to mount decrypted data");
1634 cryptfs_set_corrupt();
1635 cryptfs_trigger_restart_min_framework();
1636 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001637 if (setexeccon(NULL)) {
1638 SLOGE("Failed to setexeccon");
1639 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001640 return -1;
1641 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001642 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001643 if (setexeccon(NULL)) {
1644 SLOGE("Failed to setexeccon");
1645 return -1;
1646 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001647
Ken Sumralle5032c42012-04-01 23:58:44 -07001648 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001649 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001650 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001651
1652 /* startup service classes main and late_start */
1653 property_set("vold.decrypt", "trigger_restart_framework");
1654 SLOGD("Just triggered restart_framework\n");
1655
1656 /* Give it a few moments to get started */
1657 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001658 }
1659
Ken Sumrall0cc16632011-01-18 20:32:26 -08001660 if (rc == 0) {
1661 restart_successful = 1;
1662 }
1663
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001664 return rc;
1665}
1666
Paul Lawrencef4faa572014-01-29 13:31:03 -08001667int cryptfs_restart(void)
1668{
Paul Lawrence05335c32015-03-05 09:46:23 -08001669 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001670 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001671 SLOGE("cryptfs_restart not valid for file encryption:");
1672 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001673 }
1674
Paul Lawrencef4faa572014-01-29 13:31:03 -08001675 /* Call internal implementation forcing a restart of main service group */
1676 return cryptfs_restart_internal(1);
1677}
1678
Wei Wang4375f1b2017-02-24 17:43:01 -08001679static int do_crypto_complete(const char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001680{
1681 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001682 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001683 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001684
1685 property_get("ro.crypto.state", encrypted_state, "");
1686 if (strcmp(encrypted_state, "encrypted") ) {
1687 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001688 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001689 }
1690
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001691 // crypto_complete is full disk encrypted status
Paul Crowley38132a12016-02-09 09:50:32 +00001692 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001693 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Paul Lawrence05335c32015-03-05 09:46:23 -08001694 }
1695
Ken Sumrall160b4d62013-04-22 12:15:39 -07001696 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001697 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001698
Ken Sumralle1a45852011-12-14 21:24:27 -08001699 /*
1700 * Only report this error if key_loc is a file and it exists.
1701 * If the device was never encrypted, and /data is not mountable for
1702 * some reason, returning 1 should prevent the UI from presenting the
1703 * a "enter password" screen, or worse, a "press button to wipe the
1704 * device" screen.
1705 */
1706 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1707 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001708 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001709 } else {
1710 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001711 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001712 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001713 }
1714
Paul Lawrence74f29f12014-08-28 15:54:10 -07001715 // Test for possible error flags
1716 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1717 SLOGE("Encryption process is partway completed\n");
1718 return CRYPTO_COMPLETE_PARTIAL;
1719 }
1720
1721 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1722 SLOGE("Encryption process was interrupted but cannot continue\n");
1723 return CRYPTO_COMPLETE_INCONSISTENT;
1724 }
1725
1726 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1727 SLOGE("Encryption is successful but data is corrupt\n");
1728 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001729 }
1730
1731 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001732 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001733}
1734
Paul Lawrencef4faa572014-01-29 13:31:03 -08001735static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
Wei Wang4375f1b2017-02-24 17:43:01 -08001736 const char *passwd, const char *mount_point, const char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001737{
Greg Kaiser59ad0182018-02-16 13:01:36 -08001738 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001739 char crypto_blkdev[MAXPATHLEN];
1740 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001741 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001742 unsigned int orig_failed_decrypt_count;
1743 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001744 int use_keymaster = 0;
1745 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001746 unsigned char* intermediate_key = 0;
1747 size_t intermediate_key_size = 0;
Wei Wang4375f1b2017-02-24 17:43:01 -08001748 int N = 1 << crypt_ftr->N_factor;
1749 int r = 1 << crypt_ftr->r_factor;
1750 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001751
Paul Lawrencef4faa572014-01-29 13:31:03 -08001752 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1753 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001754
Paul Lawrencef4faa572014-01-29 13:31:03 -08001755 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001756 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1757 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001758 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001759 rc = -1;
1760 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001761 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001762 }
1763
Paul Crowleye2ee1522017-09-26 14:05:26 -07001764 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Paul Lawrencef4faa572014-01-29 13:31:03 -08001765
Paul Lawrence74f29f12014-08-28 15:54:10 -07001766 // Create crypto block device - all (non fatal) code paths
1767 // need it
Paul Crowley5afbc622017-11-27 09:42:17 -08001768 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label, 0)) {
1769 SLOGE("Error creating decrypted block device\n");
1770 rc = -1;
1771 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001772 }
1773
Paul Lawrence74f29f12014-08-28 15:54:10 -07001774 /* Work out if the problem is the password or the data */
1775 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1776 scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001777
Paul Lawrence74f29f12014-08-28 15:54:10 -07001778 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1779 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1780 N, r, p, scrypted_intermediate_key,
1781 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001782
Paul Lawrence74f29f12014-08-28 15:54:10 -07001783 // Does the key match the crypto footer?
1784 if (rc == 0 && memcmp(scrypted_intermediate_key,
1785 crypt_ftr->scrypted_intermediate_key,
1786 sizeof(scrypted_intermediate_key)) == 0) {
1787 SLOGI("Password matches");
1788 rc = 0;
1789 } else {
1790 /* Try mounting the file system anyway, just in case the problem's with
1791 * the footer, not the key. */
George Burgess IV605d7ae2016-02-29 13:39:17 -08001792 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt",
1793 mount_point);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001794 mkdir(tmp_mount_point, 0755);
Paul Crowleye2ee1522017-09-26 14:05:26 -07001795 if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001796 SLOGE("Error temp mounting decrypted block device\n");
1797 delete_crypto_blk_dev(label);
1798
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001799 rc = ++crypt_ftr->failed_decrypt_count;
1800 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001801 } else {
1802 /* Success! */
1803 SLOGI("Password did not match but decrypted drive mounted - continue");
1804 umount(tmp_mount_point);
1805 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001806 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001807 }
1808
1809 if (rc == 0) {
1810 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001811 if (orig_failed_decrypt_count != 0) {
1812 put_crypt_ftr_and_key(crypt_ftr);
1813 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001814
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001815 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001816 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001817 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001818
1819 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001820 * the key when we want to change the password on it. */
Greg Kaiser59ad0182018-02-16 13:01:36 -08001821 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001822 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001823 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001824 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001825 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001826
Paul Lawrence74f29f12014-08-28 15:54:10 -07001827 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001828 use_keymaster = keymaster_check_compatibility();
1829 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001830 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001831 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1832 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1833 upgrade = 1;
1834 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001835 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001836 upgrade = 1;
1837 }
1838
1839 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001840 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1841 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001842 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001843 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001844 }
1845 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001846
1847 // Do not fail even if upgrade failed - machine is bootable
1848 // Note that if this code is ever hit, there is a *serious* problem
1849 // since KDFs should never fail. You *must* fix the kdf before
1850 // proceeding!
1851 if (rc) {
1852 SLOGW("Upgrade failed with error %d,"
1853 " but continuing with previous state",
1854 rc);
1855 rc = 0;
1856 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001857 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001858 }
1859
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001860 errout:
1861 if (intermediate_key) {
1862 memset(intermediate_key, 0, intermediate_key_size);
1863 free(intermediate_key);
1864 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001865 return rc;
1866}
1867
Ken Sumrall29d8da82011-05-18 17:20:07 -07001868/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001869 * Called by vold when it's asked to mount an encrypted external
1870 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08001871 * as any metadata is been stored in a separate, small partition. We
1872 * assume it must be using our same crypt type and keysize.
Jeff Sharkey9c484982015-03-31 10:35:33 -07001873 *
1874 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001875 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001876int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
Greg Kaiser57f9af62018-02-16 13:13:58 -08001877 const unsigned char* key, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001878 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001879 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001880 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001881 return -1;
1882 }
1883
1884 unsigned long nr_sec = 0;
1885 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001886 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001887
Ken Sumrall29d8da82011-05-18 17:20:07 -07001888 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001889 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001890 return -1;
1891 }
1892
Jeff Sharkey9c484982015-03-31 10:35:33 -07001893 struct crypt_mnt_ftr ext_crypt_ftr;
1894 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1895 ext_crypt_ftr.fs_size = nr_sec;
Greg Kaiser57f9af62018-02-16 13:13:58 -08001896 ext_crypt_ftr.keysize = cryptfs_get_keysize();
1897 strlcpy((char*) ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001898 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07001899 uint32_t flags = 0;
1900 if (e4crypt_is_native() &&
1901 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
1902 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001903
Paul Crowley385cb8c2018-03-29 13:27:23 -07001904 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001905}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001906
Jeff Sharkey9c484982015-03-31 10:35:33 -07001907/*
1908 * Called by vold when it's asked to unmount an encrypted external
1909 * storage volume.
1910 */
1911int cryptfs_revert_ext_volume(const char* label) {
1912 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001913}
1914
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001915int cryptfs_crypto_complete(void)
1916{
1917 return do_crypto_complete("/data");
1918}
1919
Paul Lawrencef4faa572014-01-29 13:31:03 -08001920int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1921{
1922 char encrypted_state[PROPERTY_VALUE_MAX];
1923 property_get("ro.crypto.state", encrypted_state, "");
1924 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1925 SLOGE("encrypted fs already validated or not running with encryption,"
1926 " aborting");
1927 return -1;
1928 }
1929
1930 if (get_crypt_ftr_and_key(crypt_ftr)) {
1931 SLOGE("Error getting crypt footer and key");
1932 return -1;
1933 }
1934
1935 return 0;
1936}
1937
Wei Wang4375f1b2017-02-24 17:43:01 -08001938int cryptfs_check_passwd(const char *passwd)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001939{
Paul Lawrence05335c32015-03-05 09:46:23 -08001940 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00001941 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001942 SLOGE("cryptfs_check_passwd not valid for file encryption");
1943 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001944 }
1945
Paul Lawrencef4faa572014-01-29 13:31:03 -08001946 struct crypt_mnt_ftr crypt_ftr;
1947 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001948
Paul Lawrencef4faa572014-01-29 13:31:03 -08001949 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001950 if (rc) {
1951 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001952 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001953 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001954
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001955 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001956 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1957 if (rc) {
1958 SLOGE("Password did not match");
1959 return rc;
1960 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001961
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001962 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1963 // Here we have a default actual password but a real password
1964 // we must test against the scrypted value
1965 // First, we must delete the crypto block device that
1966 // test_mount_encrypted_fs leaves behind as a side effect
1967 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
1968 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
1969 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1970 if (rc) {
1971 SLOGE("Default password did not match on reboot encryption");
1972 return rc;
1973 }
1974
1975 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1976 put_crypt_ftr_and_key(&crypt_ftr);
1977 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1978 if (rc) {
1979 SLOGE("Could not change password on reboot encryption");
1980 return rc;
1981 }
1982 }
1983
1984 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001985 cryptfs_clear_password();
1986 password = strdup(passwd);
1987 struct timespec now;
1988 clock_gettime(CLOCK_BOOTTIME, &now);
1989 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001990 }
1991
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001992 return rc;
1993}
1994
Jeff Sharkey83b559c2017-09-12 16:30:52 -06001995int cryptfs_verify_passwd(const char *passwd)
Ken Sumrall3ad90722011-10-04 20:38:29 -07001996{
1997 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001998 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001999 char encrypted_state[PROPERTY_VALUE_MAX];
2000 int rc;
2001
2002 property_get("ro.crypto.state", encrypted_state, "");
2003 if (strcmp(encrypted_state, "encrypted") ) {
2004 SLOGE("device not encrypted, aborting");
2005 return -2;
2006 }
2007
2008 if (!master_key_saved) {
2009 SLOGE("encrypted fs not yet mounted, aborting");
2010 return -1;
2011 }
2012
2013 if (!saved_mount_point) {
2014 SLOGE("encrypted fs failed to save mount point, aborting");
2015 return -1;
2016 }
2017
Ken Sumrall160b4d62013-04-22 12:15:39 -07002018 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002019 SLOGE("Error getting crypt footer and key\n");
2020 return -1;
2021 }
2022
2023 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2024 /* If the device has no password, then just say the password is valid */
2025 rc = 0;
2026 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002027 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002028 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2029 /* They match, the password is correct */
2030 rc = 0;
2031 } else {
2032 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2033 sleep(1);
2034 rc = 1;
2035 }
2036 }
2037
2038 return rc;
2039}
2040
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002041/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser57f9af62018-02-16 13:13:58 -08002042 * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002043 * Presumably, at a minimum, the caller will update the
2044 * filesystem size and crypto_type_name after calling this function.
2045 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002046static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002047{
Ken Sumrall160b4d62013-04-22 12:15:39 -07002048 off64_t off;
2049
2050 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002051 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002052 ftr->major_version = CURRENT_MAJOR_VERSION;
2053 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002054 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser57f9af62018-02-16 13:13:58 -08002055 ftr->keysize = cryptfs_get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07002056
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002057 switch (keymaster_check_compatibility()) {
2058 case 1:
2059 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2060 break;
2061
2062 case 0:
2063 ftr->kdf_type = KDF_SCRYPT;
2064 break;
2065
2066 default:
2067 SLOGE("keymaster_check_compatibility failed");
2068 return -1;
2069 }
2070
Kenny Rootc4c70f12013-06-14 12:11:38 -07002071 get_device_scrypt_params(ftr);
2072
Ken Sumrall160b4d62013-04-22 12:15:39 -07002073 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2074 if (get_crypt_ftr_info(NULL, &off) == 0) {
2075 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
2076 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
2077 ftr->persist_data_size;
2078 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002079
2080 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002081}
2082
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002083#define FRAMEWORK_BOOT_WAIT 60
2084
Paul Lawrence87999172014-02-20 12:21:31 -08002085static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2086{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002087 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002088 if (fd == -1) {
2089 SLOGE("Error opening file %s", filename);
2090 return -1;
2091 }
2092
2093 char block[CRYPT_INPLACE_BUFSIZE];
2094 memset(block, 0, sizeof(block));
2095 if (unix_read(fd, block, sizeof(block)) < 0) {
2096 SLOGE("Error reading file %s", filename);
2097 close(fd);
2098 return -1;
2099 }
2100
2101 close(fd);
2102
2103 SHA256_CTX c;
2104 SHA256_Init(&c);
2105 SHA256_Update(&c, block, sizeof(block));
2106 SHA256_Final(buf, &c);
2107
2108 return 0;
2109}
2110
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002111static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
2112 char* real_blkdev, int previously_encrypted_upto) {
Paul Lawrence87999172014-02-20 12:21:31 -08002113 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002114 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002115
Paul Lawrence87999172014-02-20 12:21:31 -08002116 /* The size of the userdata partition, and add in the vold volumes below */
2117 tot_encryption_size = crypt_ftr->fs_size;
2118
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002119 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002120 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002121
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002122 if (rc == ENABLE_INPLACE_ERR_DEV) {
2123 /* Hack for b/17898962 */
2124 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2125 cryptfs_reboot(RebootType::reboot);
2126 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002127
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002128 if (!rc) {
2129 crypt_ftr->encrypted_upto = cur_encryption_done;
2130 }
Paul Lawrence87999172014-02-20 12:21:31 -08002131
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002132 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2133 /* The inplace routine never actually sets the progress to 100% due
2134 * to the round down nature of integer division, so set it here */
2135 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002136 }
2137
2138 return rc;
2139}
2140
Paul Crowleyb64933a2017-10-31 08:25:55 -07002141static int vold_unmountAll(void) {
2142 VolumeManager* vm = VolumeManager::Instance();
2143 return vm->unmountAll();
2144}
2145
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002146int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Lawrence87999172014-02-20 12:21:31 -08002147 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Greg Kaiser59ad0182018-02-16 13:01:36 -08002148 unsigned char decrypted_master_key[MAX_KEY_LEN];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002149 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002150 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002151 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002152 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002153 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002154 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002155 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002156 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002157 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002158 bool onlyCreateHeader = false;
2159 int fd = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002160
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002161 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002162 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2163 /* An encryption was underway and was interrupted */
2164 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2165 crypt_ftr.encrypted_upto = 0;
2166 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002167
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002168 /* At this point, we are in an inconsistent state. Until we successfully
2169 complete encryption, a reboot will leave us broken. So mark the
2170 encryption failed in case that happens.
2171 On successfully completing encryption, remove this flag */
2172 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002173
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002174 put_crypt_ftr_and_key(&crypt_ftr);
2175 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2176 if (!check_ftr_sha(&crypt_ftr)) {
2177 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2178 put_crypt_ftr_and_key(&crypt_ftr);
2179 goto error_unencrypted;
2180 }
2181
2182 /* Doing a reboot-encryption*/
2183 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2184 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2185 rebootEncryption = true;
2186 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002187 } else {
2188 // We don't want to accidentally reference invalid data.
2189 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002190 }
2191
2192 property_get("ro.crypto.state", encrypted_state, "");
2193 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2194 SLOGE("Device is already running encrypted, aborting");
2195 goto error_unencrypted;
2196 }
2197
2198 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002199 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2200 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002201
Ken Sumrall3ed82362011-01-28 23:31:16 -08002202 /* Get the size of the real block device */
Wei Wang4375f1b2017-02-24 17:43:01 -08002203 fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002204 if (fd == -1) {
2205 SLOGE("Cannot open block device %s\n", real_blkdev);
2206 goto error_unencrypted;
2207 }
2208 unsigned long nr_sec;
2209 get_blkdev_size(fd, &nr_sec);
2210 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002211 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2212 goto error_unencrypted;
2213 }
2214 close(fd);
2215
2216 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002217 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002218 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002219 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002220 if (fs_size_sec == 0)
2221 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2222
Paul Lawrence87999172014-02-20 12:21:31 -08002223 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002224
2225 if (fs_size_sec > max_fs_size_sec) {
2226 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2227 goto error_unencrypted;
2228 }
2229 }
2230
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002231 /* Get a wakelock as this may take a while, and we don't want the
2232 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2233 * wants to keep the screen on, it can grab a full wakelock.
2234 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002235 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002236 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2237
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002238 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002239 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002240 */
2241 property_set("vold.decrypt", "trigger_shutdown_framework");
2242 SLOGD("Just asked init to shut down class main\n");
2243
Jeff Sharkey9c484982015-03-31 10:35:33 -07002244 /* Ask vold to unmount all devices that it manages */
2245 if (vold_unmountAll()) {
2246 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002247 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002248
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002249 /* no_ui means we are being called from init, not settings.
2250 Now we always reboot from settings, so !no_ui means reboot
2251 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002252 if (!no_ui) {
2253 /* Try fallback, which is to reboot and try there */
2254 onlyCreateHeader = true;
2255 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2256 if (breadcrumb == 0) {
2257 SLOGE("Failed to create breadcrumb file");
2258 goto error_shutting_down;
2259 }
2260 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002261 }
2262
2263 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002264 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002265 /* Now that /data is unmounted, we need to mount a tmpfs
2266 * /data, set a property saying we're doing inplace encryption,
2267 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002268 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002269 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002270 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002271 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002272 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002273 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002274
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002275 /* restart the framework. */
2276 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002277 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002278
Ken Sumrall92736ef2012-10-17 20:57:14 -07002279 /* Ugh, shutting down the framework is not synchronous, so until it
2280 * can be fixed, this horrible hack will wait a moment for it all to
2281 * shut down before proceeding. Without it, some devices cannot
2282 * restart the graphics services.
2283 */
2284 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002285 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002286
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002287 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002288 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002289 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002290 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2291 goto error_shutting_down;
2292 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002293
Paul Lawrence87999172014-02-20 12:21:31 -08002294 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2295 crypt_ftr.fs_size = nr_sec
2296 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2297 } else {
2298 crypt_ftr.fs_size = nr_sec;
2299 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002300 /* At this point, we are in an inconsistent state. Until we successfully
2301 complete encryption, a reboot will leave us broken. So mark the
2302 encryption failed in case that happens.
2303 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002304 if (onlyCreateHeader) {
2305 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2306 } else {
2307 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2308 }
Paul Lawrence87999172014-02-20 12:21:31 -08002309 crypt_ftr.crypt_type = crypt_type;
Greg Kaiser57f9af62018-02-16 13:13:58 -08002310 strlcpy((char *)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(), MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002311
Paul Lawrence87999172014-02-20 12:21:31 -08002312 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002313 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2314 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002315 SLOGE("Cannot create encrypted master key\n");
2316 goto error_shutting_down;
2317 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002318
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002319 /* Replace scrypted intermediate key if we are preparing for a reboot */
2320 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002321 unsigned char fake_master_key[MAX_KEY_LEN];
2322 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002323 memset(fake_master_key, 0, sizeof(fake_master_key));
2324 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
2325 encrypted_fake_master_key, &crypt_ftr);
2326 }
2327
Paul Lawrence87999172014-02-20 12:21:31 -08002328 /* Write the key to the end of the partition */
2329 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002330
Paul Lawrence87999172014-02-20 12:21:31 -08002331 /* If any persistent data has been remembered, save it.
2332 * If none, create a valid empty table and save that.
2333 */
2334 if (!persist_data) {
Wei Wang4375f1b2017-02-24 17:43:01 -08002335 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002336 if (pdata) {
2337 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2338 persist_data = pdata;
2339 }
2340 }
2341 if (persist_data) {
2342 save_persistent_data();
2343 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002344 }
2345
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002346 if (onlyCreateHeader) {
2347 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002348 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002349 }
2350
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002351 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002352 /* startup service classes main and late_start */
2353 property_set("vold.decrypt", "trigger_restart_min_framework");
2354 SLOGD("Just triggered restart_min_framework\n");
2355
2356 /* OK, the framework is restarted and will soon be showing a
2357 * progress bar. Time to setup an encrypted mapping, and
2358 * either write a new filesystem, or encrypt in place updating
2359 * the progress bar as we work.
2360 */
2361 }
2362
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002363 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002364 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002365 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002366
Paul Lawrence87999172014-02-20 12:21:31 -08002367 /* If we are continuing, check checksums match */
2368 rc = 0;
2369 if (previously_encrypted_upto) {
2370 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2371 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002372
Paul Lawrence87999172014-02-20 12:21:31 -08002373 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2374 sizeof(hash_first_block)) != 0) {
2375 SLOGE("Checksums do not match - trigger wipe");
2376 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002377 }
2378 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002379
Paul Lawrence87999172014-02-20 12:21:31 -08002380 if (!rc) {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002381 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002382 previously_encrypted_upto);
2383 }
2384
2385 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002386 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002387 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2388 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002389 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002390 SLOGE("Error calculating checksum for continuing encryption");
2391 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002392 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002393 }
2394
2395 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002396 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002397
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002398 if (! rc) {
2399 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002400 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002401
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002402 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002403 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2404 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002405 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002406 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002407
Paul Lawrence6bfed202014-07-28 12:47:22 -07002408 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002409
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002410 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2411 char value[PROPERTY_VALUE_MAX];
2412 property_get("ro.crypto.state", value, "");
2413 if (!strcmp(value, "")) {
2414 /* default encryption - continue first boot sequence */
2415 property_set("ro.crypto.state", "encrypted");
2416 property_set("ro.crypto.type", "block");
2417 release_wake_lock(lockid);
2418 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2419 // Bring up cryptkeeper that will check the password and set it
2420 property_set("vold.decrypt", "trigger_shutdown_framework");
2421 sleep(2);
2422 property_set("vold.encrypt_progress", "");
2423 cryptfs_trigger_restart_min_framework();
2424 } else {
2425 cryptfs_check_passwd(DEFAULT_PASSWORD);
2426 cryptfs_restart_internal(1);
2427 }
2428 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002429 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002430 sleep(2); /* Give the UI a chance to show 100% progress */
2431 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002432 }
Paul Lawrence87999172014-02-20 12:21:31 -08002433 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002434 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002435 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002436 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002437 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002438 char value[PROPERTY_VALUE_MAX];
2439
Ken Sumrall319369a2012-06-27 16:30:18 -07002440 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002441 if (!strcmp(value, "1")) {
2442 /* wipe data if encryption failed */
2443 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002444 std::string err;
2445 const std::vector<std::string> options = {
2446 "--wipe_data\n--reason=cryptfs_enable_internal\n"
2447 };
2448 if (!write_bootloader_message(options, &err)) {
2449 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002450 }
Josh Gaofec44372017-08-28 13:22:55 -07002451 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002452 } else {
2453 /* set property to trigger dialog */
2454 property_set("vold.encrypt_progress", "error_partially_encrypted");
2455 release_wake_lock(lockid);
2456 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002457 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002458 }
2459
Ken Sumrall3ed82362011-01-28 23:31:16 -08002460 /* hrm, the encrypt step claims success, but the reboot failed.
2461 * This should not happen.
2462 * Set the property and return. Hope the framework can deal with it.
2463 */
2464 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002465 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002466 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002467
2468error_unencrypted:
2469 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002470 if (lockid[0]) {
2471 release_wake_lock(lockid);
2472 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002473 return -1;
2474
2475error_shutting_down:
2476 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2477 * but the framework is stopped and not restarted to show the error, so it's up to
2478 * vold to restart the system.
2479 */
2480 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Josh Gaofec44372017-08-28 13:22:55 -07002481 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002482
2483 /* shouldn't get here */
2484 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002485 if (lockid[0]) {
2486 release_wake_lock(lockid);
2487 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002488 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002489}
2490
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002491int cryptfs_enable(int type, const char* passwd, int no_ui) {
2492 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002493}
2494
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002495int cryptfs_enable_default(int no_ui) {
2496 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002497}
2498
2499int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002500{
Paul Crowley38132a12016-02-09 09:50:32 +00002501 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002502 SLOGE("cryptfs_changepw not valid for file encryption");
2503 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002504 }
2505
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002506 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002507 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002508
2509 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002510 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002511 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002512 return -1;
2513 }
2514
Paul Lawrencef4faa572014-01-29 13:31:03 -08002515 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2516 SLOGE("Invalid crypt_type %d", crypt_type);
2517 return -1;
2518 }
2519
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002520 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002521 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002522 SLOGE("Error getting crypt footer and key");
2523 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002524 }
2525
Paul Lawrencef4faa572014-01-29 13:31:03 -08002526 crypt_ftr.crypt_type = crypt_type;
2527
JP Abgrall933216c2015-02-11 13:44:32 -08002528 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08002529 : newpw,
2530 crypt_ftr.salt,
2531 saved_master_key,
2532 crypt_ftr.master_key,
2533 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002534 if (rc) {
2535 SLOGE("Encrypt master key failed: %d", rc);
2536 return -1;
2537 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002538 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002539 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002540
2541 return 0;
2542}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002543
Rubin Xu85c01f92014-10-13 12:49:54 +01002544static unsigned int persist_get_max_entries(int encrypted) {
2545 struct crypt_mnt_ftr crypt_ftr;
2546 unsigned int dsize;
2547 unsigned int max_persistent_entries;
2548
2549 /* If encrypted, use the values from the crypt_ftr, otherwise
2550 * use the values for the current spec.
2551 */
2552 if (encrypted) {
2553 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2554 return -1;
2555 }
2556 dsize = crypt_ftr.persist_data_size;
2557 } else {
2558 dsize = CRYPT_PERSIST_DATA_SIZE;
2559 }
2560
2561 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2562 sizeof(struct crypt_persist_entry);
2563
2564 return max_persistent_entries;
2565}
2566
2567static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002568{
2569 unsigned int i;
2570
2571 if (persist_data == NULL) {
2572 return -1;
2573 }
2574 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2575 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2576 /* We found it! */
2577 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2578 return 0;
2579 }
2580 }
2581
2582 return -1;
2583}
2584
Rubin Xu85c01f92014-10-13 12:49:54 +01002585static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002586{
2587 unsigned int i;
2588 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002589 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002590
2591 if (persist_data == NULL) {
2592 return -1;
2593 }
2594
Rubin Xu85c01f92014-10-13 12:49:54 +01002595 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002596
2597 num = persist_data->persist_valid_entries;
2598
2599 for (i = 0; i < num; i++) {
2600 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2601 /* We found an existing entry, update it! */
2602 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2603 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2604 return 0;
2605 }
2606 }
2607
2608 /* We didn't find it, add it to the end, if there is room */
2609 if (persist_data->persist_valid_entries < max_persistent_entries) {
2610 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2611 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2612 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2613 persist_data->persist_valid_entries++;
2614 return 0;
2615 }
2616
2617 return -1;
2618}
2619
Rubin Xu85c01f92014-10-13 12:49:54 +01002620/**
2621 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2622 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2623 */
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002624int match_multi_entry(const char *key, const char *field, unsigned index) {
2625 std::string key_ = key;
2626 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002627
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002628 std::string parsed_field;
2629 unsigned parsed_index;
2630
2631 std::string::size_type split = key_.find_last_of('_');
2632 if (split == std::string::npos) {
2633 parsed_field = key_;
2634 parsed_index = 0;
2635 } else {
2636 parsed_field = key_.substr(0, split);
2637 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002638 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002639
2640 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002641}
2642
2643/*
2644 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2645 * remaining entries starting from index will be deleted.
2646 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2647 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2648 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2649 *
2650 */
2651static int persist_del_keys(const char *fieldname, unsigned index)
2652{
2653 unsigned int i;
2654 unsigned int j;
2655 unsigned int num;
2656
2657 if (persist_data == NULL) {
2658 return PERSIST_DEL_KEY_ERROR_OTHER;
2659 }
2660
2661 num = persist_data->persist_valid_entries;
2662
2663 j = 0; // points to the end of non-deleted entries.
2664 // Filter out to-be-deleted entries in place.
2665 for (i = 0; i < num; i++) {
2666 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2667 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2668 j++;
2669 }
2670 }
2671
2672 if (j < num) {
2673 persist_data->persist_valid_entries = j;
2674 // Zeroise the remaining entries
2675 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2676 return PERSIST_DEL_KEY_OK;
2677 } else {
2678 // Did not find an entry matching the given fieldname
2679 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2680 }
2681}
2682
2683static int persist_count_keys(const char *fieldname)
2684{
2685 unsigned int i;
2686 unsigned int count;
2687
2688 if (persist_data == NULL) {
2689 return -1;
2690 }
2691
2692 count = 0;
2693 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2694 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2695 count++;
2696 }
2697 }
2698
2699 return count;
2700}
2701
Ken Sumrall160b4d62013-04-22 12:15:39 -07002702/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002703int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002704{
Paul Crowley38132a12016-02-09 09:50:32 +00002705 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002706 SLOGE("Cannot get field when file encrypted");
2707 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002708 }
2709
Ken Sumrall160b4d62013-04-22 12:15:39 -07002710 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002711 /* CRYPTO_GETFIELD_OK is success,
2712 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2713 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2714 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002715 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002716 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2717 int i;
2718 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002719
2720 if (persist_data == NULL) {
2721 load_persistent_data();
2722 if (persist_data == NULL) {
2723 SLOGE("Getfield error, cannot load persistent data");
2724 goto out;
2725 }
2726 }
2727
Rubin Xu85c01f92014-10-13 12:49:54 +01002728 // Read value from persistent entries. If the original value is split into multiple entries,
2729 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002730 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002731 // We found it, copy it to the caller's buffer and keep going until all entries are read.
2732 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
2733 // value too small
2734 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2735 goto out;
2736 }
2737 rc = CRYPTO_GETFIELD_OK;
2738
2739 for (i = 1; /* break explicitly */; i++) {
2740 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
2741 (int) sizeof(temp_field)) {
2742 // If the fieldname is very long, we stop as soon as it begins to overflow the
2743 // maximum field length. At this point we have in fact fully read out the original
2744 // value because cryptfs_setfield would not allow fields with longer names to be
2745 // written in the first place.
2746 break;
2747 }
2748 if (!persist_get_key(temp_field, temp_value)) {
2749 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2750 // value too small.
2751 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2752 goto out;
2753 }
2754 } else {
2755 // Exhaust all entries.
2756 break;
2757 }
2758 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002759 } else {
2760 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002761 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002762 }
2763
2764out:
2765 return rc;
2766}
2767
2768/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002769int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002770{
Paul Crowley38132a12016-02-09 09:50:32 +00002771 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002772 SLOGE("Cannot set field when file encrypted");
2773 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002774 }
2775
Ken Sumrall160b4d62013-04-22 12:15:39 -07002776 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002777 /* 0 is success, negative values are error */
2778 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002779 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002780 unsigned int field_id;
2781 char temp_field[PROPERTY_KEY_MAX];
2782 unsigned int num_entries;
2783 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002784
2785 if (persist_data == NULL) {
2786 load_persistent_data();
2787 if (persist_data == NULL) {
2788 SLOGE("Setfield error, cannot load persistent data");
2789 goto out;
2790 }
2791 }
2792
2793 property_get("ro.crypto.state", encrypted_state, "");
2794 if (!strcmp(encrypted_state, "encrypted") ) {
2795 encrypted = 1;
2796 }
2797
Rubin Xu85c01f92014-10-13 12:49:54 +01002798 // Compute the number of entries required to store value, each entry can store up to
2799 // (PROPERTY_VALUE_MAX - 1) chars
2800 if (strlen(value) == 0) {
2801 // Empty value also needs one entry to store.
2802 num_entries = 1;
2803 } else {
2804 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2805 }
2806
2807 max_keylen = strlen(fieldname);
2808 if (num_entries > 1) {
2809 // Need an extra "_%d" suffix.
2810 max_keylen += 1 + log10(num_entries);
2811 }
2812 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2813 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002814 goto out;
2815 }
2816
Rubin Xu85c01f92014-10-13 12:49:54 +01002817 // Make sure we have enough space to write the new value
2818 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2819 persist_get_max_entries(encrypted)) {
2820 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2821 goto out;
2822 }
2823
2824 // Now that we know persist_data has enough space for value, let's delete the old field first
2825 // to make up space.
2826 persist_del_keys(fieldname, 0);
2827
2828 if (persist_set_key(fieldname, value, encrypted)) {
2829 // fail to set key, should not happen as we have already checked the available space
2830 SLOGE("persist_set_key() error during setfield()");
2831 goto out;
2832 }
2833
2834 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002835 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002836
2837 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2838 // fail to set key, should not happen as we have already checked the available space.
2839 SLOGE("persist_set_key() error during setfield()");
2840 goto out;
2841 }
2842 }
2843
Ken Sumrall160b4d62013-04-22 12:15:39 -07002844 /* If we are running encrypted, save the persistent data now */
2845 if (encrypted) {
2846 if (save_persistent_data()) {
2847 SLOGE("Setfield error, cannot save persistent data");
2848 goto out;
2849 }
2850 }
2851
Rubin Xu85c01f92014-10-13 12:49:54 +01002852 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002853
2854out:
2855 return rc;
2856}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002857
2858/* Checks userdata. Attempt to mount the volume if default-
2859 * encrypted.
2860 * On success trigger next init phase and return 0.
2861 * Currently do not handle failure - see TODO below.
2862 */
2863int cryptfs_mount_default_encrypted(void)
2864{
Paul Lawrence84274cc2016-04-15 15:41:33 -07002865 int crypt_type = cryptfs_get_password_type();
2866 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2867 SLOGE("Bad crypt type - error");
2868 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2869 SLOGD("Password is not default - "
2870 "starting min framework to prompt");
2871 property_set("vold.decrypt", "trigger_restart_min_framework");
2872 return 0;
2873 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2874 SLOGD("Password is default - restarting filesystem");
2875 cryptfs_restart_internal(0);
2876 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002877 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002878 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002879 }
2880
Paul Lawrence6bfed202014-07-28 12:47:22 -07002881 /** Corrupt. Allow us to boot into framework, which will detect bad
2882 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002883 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002884 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002885 return 0;
2886}
2887
2888/* Returns type of the password, default, pattern, pin or password.
2889 */
2890int cryptfs_get_password_type(void)
2891{
Paul Crowley38132a12016-02-09 09:50:32 +00002892 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002893 SLOGE("cryptfs_get_password_type not valid for file encryption");
2894 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002895 }
2896
Paul Lawrencef4faa572014-01-29 13:31:03 -08002897 struct crypt_mnt_ftr crypt_ftr;
2898
2899 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2900 SLOGE("Error getting crypt footer and key\n");
2901 return -1;
2902 }
2903
Paul Lawrence6bfed202014-07-28 12:47:22 -07002904 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2905 return -1;
2906 }
2907
Paul Lawrencef4faa572014-01-29 13:31:03 -08002908 return crypt_ftr.crypt_type;
2909}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002910
Paul Lawrence05335c32015-03-05 09:46:23 -08002911const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002912{
Paul Crowley38132a12016-02-09 09:50:32 +00002913 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002914 SLOGE("cryptfs_get_password not valid for file encryption");
2915 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002916 }
2917
Paul Lawrence399317e2014-03-10 13:20:50 -07002918 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002919 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002920 if (now.tv_sec < password_expiry_time) {
2921 return password;
2922 } else {
2923 cryptfs_clear_password();
2924 return 0;
2925 }
2926}
2927
2928void cryptfs_clear_password()
2929{
2930 if (password) {
2931 size_t len = strlen(password);
2932 memset(password, 0, len);
2933 free(password);
2934 password = 0;
2935 password_expiry_time = 0;
2936 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002937}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002938
Paul Lawrence0c247462015-10-29 10:30:57 -07002939int cryptfs_isConvertibleToFBE()
2940{
Paul Crowleye2ee1522017-09-26 14:05:26 -07002941 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Paul Lawrence0c247462015-10-29 10:30:57 -07002942 return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
2943}