blob: 234899e9a7fb9a43b25d1c7eaf0394146be681e8 [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
Jason parks70a4b3f2011-01-28 10:10:47 -060075#define IV_LEN_BYTES 16
76
Ken Sumrall29d8da82011-05-18 17:20:07 -070077#define KEY_IN_FOOTER "footer"
78
Paul Lawrence3bd36d52015-06-09 13:37:44 -070079#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080080
Paul Lawrence3d99eba2015-11-20 07:07:19 -080081#define CRYPTO_BLOCK_DEVICE "userdata"
82
83#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
84
Ken Sumrall29d8da82011-05-18 17:20:07 -070085#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070086#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070087
Ken Sumralle919efe2012-09-29 17:07:41 -070088#define TABLE_LOAD_RETRIES 10
89
Shawn Willden47ba10d2014-09-03 17:07:06 -060090#define RSA_KEY_SIZE 2048
91#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
92#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -060093#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070094
Paul Lawrence8e3f4512014-09-08 10:11:17 -070095#define RETRY_MOUNT_ATTEMPTS 10
96#define RETRY_MOUNT_DELAY_SECONDS 1
97
Paul Crowley5afbc622017-11-27 09:42:17 -080098#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
99
Greg Kaiser4a35ef02018-02-09 17:01:06 -0800100// EVP_DecryptUpdate() requires not just our key length, but up to
101// block length - 1 additional bytes for its work. We provide a buffer
102// size that will work for all possible ciphers.
Greg Kaiser291fec12018-02-09 18:24:59 -0800103#define DECRYPTED_MASTER_KEY_BUF_SIZE (MAX_KEY_LEN + EVP_MAX_BLOCK_LENGTH - 1)
Greg Kaiser4a35ef02018-02-09 17:01:06 -0800104
Paul Crowley73473332017-11-21 15:43:51 -0800105static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
106
Greg Kaiser291fec12018-02-09 18:24:59 -0800107static unsigned char saved_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -0700108static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -0600109static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700110static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800111
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700112/* Should we use keymaster? */
113static int keymaster_check_compatibility()
114{
Janis Danisevskis015ec302017-01-31 11:31:08 +0000115 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700116}
117
118/* Create a new keymaster key and store it in this footer */
119static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
120{
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800121 if (ftr->keymaster_blob_size) {
122 SLOGI("Already have key");
123 return 0;
124 }
125
Janis Danisevskis015ec302017-01-31 11:31:08 +0000126 int rc = keymaster_create_key_for_cryptfs_scrypt(RSA_KEY_SIZE, RSA_EXPONENT,
127 KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
128 &ftr->keymaster_blob_size);
129 if (rc) {
130 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800131 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000132 ftr->keymaster_blob_size = 0;
133 }
134 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700135 return -1;
136 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000137 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700138}
139
Shawn Willdene17a9c42014-09-08 13:04:08 -0600140/* This signs the given object using the keymaster key. */
141static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600142 const unsigned char *object,
143 const size_t object_size,
144 unsigned char **signature,
145 size_t *signature_size)
146{
Shawn Willden47ba10d2014-09-03 17:07:06 -0600147 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600148 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600149 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600150
Shawn Willdene17a9c42014-09-08 13:04:08 -0600151 // To sign a message with RSA, the message must satisfy two
152 // constraints:
153 //
154 // 1. The message, when interpreted as a big-endian numeric value, must
155 // be strictly less than the public modulus of the RSA key. Note
156 // that because the most significant bit of the public modulus is
157 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
158 // key), an n-bit message with most significant bit 0 always
159 // satisfies this requirement.
160 //
161 // 2. The message must have the same length in bits as the public
162 // modulus of the RSA key. This requirement isn't mathematically
163 // necessary, but is necessary to ensure consistency in
164 // implementations.
165 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600166 case KDF_SCRYPT_KEYMASTER:
167 // This ensures the most significant byte of the signed message
168 // is zero. We could have zero-padded to the left instead, but
169 // this approach is slightly more robust against changes in
170 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600171 // so) because we really should be using a proper deterministic
172 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800173 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600174 SLOGI("Signing safely-padded object");
175 break;
176 default:
177 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000178 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600179 }
Paul Crowley73473332017-11-21 15:43:51 -0800180 for (;;) {
181 auto result = keymaster_sign_object_for_cryptfs_scrypt(
182 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
183 to_sign_size, signature, signature_size);
184 switch (result) {
185 case KeymasterSignResult::ok:
186 return 0;
187 case KeymasterSignResult::upgrade:
188 break;
189 default:
190 return -1;
191 }
192 SLOGD("Upgrading key");
193 if (keymaster_upgrade_key_for_cryptfs_scrypt(
194 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
195 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
196 &ftr->keymaster_blob_size) != 0) {
197 SLOGE("Failed to upgrade key");
198 return -1;
199 }
200 if (put_crypt_ftr_and_key(ftr) != 0) {
201 SLOGE("Failed to write upgraded key to disk");
202 }
203 SLOGD("Key upgraded successfully");
204 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600205}
206
Paul Lawrence399317e2014-03-10 13:20:50 -0700207/* Store password when userdata is successfully decrypted and mounted.
208 * Cleared by cryptfs_clear_password
209 *
210 * To avoid a double prompt at boot, we need to store the CryptKeeper
211 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
212 * Since the entire framework is torn down and rebuilt after encryption,
213 * we have to use a daemon or similar to store the password. Since vold
214 * is secured against IPC except from system processes, it seems a reasonable
215 * place to store this.
216 *
217 * password should be cleared once it has been used.
218 *
219 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800220 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700221static char* password = 0;
222static int password_expiry_time = 0;
223static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800224
Josh Gaofec44372017-08-28 13:22:55 -0700225enum class RebootType {reboot, recovery, shutdown};
226static void cryptfs_reboot(RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700227{
Josh Gaofec44372017-08-28 13:22:55 -0700228 switch (rt) {
229 case RebootType::reboot:
Paul Lawrence87999172014-02-20 12:21:31 -0800230 property_set(ANDROID_RB_PROPERTY, "reboot");
231 break;
232
Josh Gaofec44372017-08-28 13:22:55 -0700233 case RebootType::recovery:
Paul Lawrence87999172014-02-20 12:21:31 -0800234 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
235 break;
236
Josh Gaofec44372017-08-28 13:22:55 -0700237 case RebootType::shutdown:
Paul Lawrence87999172014-02-20 12:21:31 -0800238 property_set(ANDROID_RB_PROPERTY, "shutdown");
239 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700240 }
Paul Lawrence87999172014-02-20 12:21:31 -0800241
Ken Sumralladfba362013-06-04 16:37:52 -0700242 sleep(20);
243
244 /* Shouldn't get here, reboot should happen before sleep times out */
245 return;
246}
247
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800248static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
249{
250 memset(io, 0, dataSize);
251 io->data_size = dataSize;
252 io->data_start = sizeof(struct dm_ioctl);
253 io->version[0] = 4;
254 io->version[1] = 0;
255 io->version[2] = 0;
256 io->flags = flags;
257 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100258 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800259 }
260}
261
Greg Kaiser291fec12018-02-09 18:24:59 -0800262namespace {
263
264struct CryptType;
265
266// Use to get the CryptType in use on this device.
267const CryptType &get_crypt_type();
268
269struct CryptType {
270 const char * name;
271 __le32 keysize;
272
273 constexpr CryptType(const char *n, size_t size) : name(n), keysize(size) {}
274
275 private:
276 friend const CryptType &get_crypt_type();
277 static const CryptType &get_device_crypt_name();
278};
279
280// We only want to parse this read-only property once. But we need to wait
281// until the system is initialized before we can read it. So we use a static
282// scoped within this function to get it only once.
283const CryptType &get_crypt_type() {
284 static CryptType crypt_type = CryptType::get_device_crypt_name();
285 return crypt_type;
286}
287
288__le32 get_keysize() {
289 return get_crypt_type().keysize;
290}
291
292const char *get_crypt_name() {
293 return get_crypt_type().name;
294}
295
296
297
298constexpr CryptType default_crypt_type = CryptType("aes-cbc-essiv:sha256", 16);
299
300constexpr CryptType supported_crypt_types[] = {
301 default_crypt_type,
302 CryptType("speck128-xts-plain64", 32),
303 // Add new CryptTypes here. Order is not important.
304};
305
306
307// ---------- START COMPILE-TIME SANITY CHECK BLOCK -------------------------
308// We confirm all supported_crypt_types have a small enough keysize.
309
310template <typename T, size_t N>
311constexpr size_t array_length(T (&)[N]) { return N; }
312
313constexpr bool indexOutOfBoundsForCryptTypes(size_t index) {
314 return (index >= array_length(supported_crypt_types));
315}
316
317// Note in C++11 that constexpr functions can only have a single line.
318// So our code is a bit convoluted (using recursion instead of a loop),
319// but it's asserting at compile time that all of our key lengths are valid.
320constexpr bool validateSupportedCryptTypes(size_t index) {
321 return indexOutOfBoundsForCryptTypes(index) ||
322 ((supported_crypt_types[index].keysize <= MAX_KEY_LEN) &&
323 validateSupportedCryptTypes(index + 1));
324}
325
326static_assert(validateSupportedCryptTypes(0),
327 "We have a CryptType with keysize > MAX_KEYSIZE");
328// ---------- END COMPILE-TIME SANITY CHECK BLOCK -------------------------
329
330
331// Don't call this directly, use get_crypt_type(), which caches this result.
332const CryptType &CryptType::get_device_crypt_name() {
333 constexpr char CRYPT_TYPE_PROP[] = "ro.crypto.crypt_type_name";
334 char paramstr[PROPERTY_VALUE_MAX];
335
336 property_get(CRYPT_TYPE_PROP, paramstr, default_crypt_type.name);
337 for (auto const &ctype : supported_crypt_types) {
338 if (strcmp(paramstr, ctype.name) == 0) {
339 return ctype;
340 }
341 }
342 ALOGE("Invalid name (%s) for %s. Defaulting to %s\n", paramstr,
343 CRYPT_TYPE_PROP, default_crypt_type.name);
344 return default_crypt_type;
345}
346
347} // namespace
348
349
Kenny Rootc4c70f12013-06-14 12:11:38 -0700350/**
351 * Gets the default device scrypt parameters for key derivation time tuning.
352 * The parameters should lead to about one second derivation time for the
353 * given device.
354 */
355static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700356 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000357 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700358
Paul Crowley63c18d32016-02-10 14:02:47 +0000359 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
360 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
361 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
362 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700363 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000364 ftr->N_factor = Nf;
365 ftr->r_factor = rf;
366 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700367}
368
Ken Sumrall3ed82362011-01-28 23:31:16 -0800369static unsigned int get_fs_size(char *dev)
370{
371 int fd, block_size;
372 struct ext4_super_block sb;
373 off64_t len;
374
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700375 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800376 SLOGE("Cannot open device to get filesystem size ");
377 return 0;
378 }
379
380 if (lseek64(fd, 1024, SEEK_SET) < 0) {
381 SLOGE("Cannot seek to superblock");
382 return 0;
383 }
384
385 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
386 SLOGE("Cannot read superblock");
387 return 0;
388 }
389
390 close(fd);
391
Daniel Rosenberge82df162014-08-15 22:19:23 +0000392 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
393 SLOGE("Not a valid ext4 superblock");
394 return 0;
395 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800396 block_size = 1024 << sb.s_log_block_size;
397 /* compute length in bytes */
398 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
399
400 /* return length in sectors */
401 return (unsigned int) (len / 512);
402}
403
Ken Sumrall160b4d62013-04-22 12:15:39 -0700404static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
405{
406 static int cached_data = 0;
407 static off64_t cached_off = 0;
408 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
409 int fd;
410 char key_loc[PROPERTY_VALUE_MAX];
411 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700412 int rc = -1;
413
414 if (!cached_data) {
Paul Crowleye2ee1522017-09-26 14:05:26 -0700415 fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700416
417 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700418 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700419 SLOGE("Cannot open real block device %s\n", real_blkdev);
420 return -1;
421 }
422
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900423 unsigned long nr_sec = 0;
424 get_blkdev_size(fd, &nr_sec);
425 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700426 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
427 * encryption info footer and key, and plenty of bytes to spare for future
428 * growth.
429 */
430 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
431 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
432 cached_data = 1;
433 } else {
434 SLOGE("Cannot get size of block device %s\n", real_blkdev);
435 }
436 close(fd);
437 } else {
438 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
439 cached_off = 0;
440 cached_data = 1;
441 }
442 }
443
444 if (cached_data) {
445 if (metadata_fname) {
446 *metadata_fname = cached_metadata_fname;
447 }
448 if (off) {
449 *off = cached_off;
450 }
451 rc = 0;
452 }
453
454 return rc;
455}
456
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800457/* Set sha256 checksum in structure */
458static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr)
459{
460 SHA256_CTX c;
461 SHA256_Init(&c);
462 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
463 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
464 SHA256_Final(crypt_ftr->sha256, &c);
465}
466
Ken Sumralle8744072011-01-18 22:01:55 -0800467/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800468 * update the failed mount count but not change the key.
469 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700470static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800471{
472 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800473 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700474 /* starting_off is set to the SEEK_SET offset
475 * where the crypto structure starts
476 */
477 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800478 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700479 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700480 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800481
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800482 set_ftr_sha(crypt_ftr);
483
Ken Sumrall160b4d62013-04-22 12:15:39 -0700484 if (get_crypt_ftr_info(&fname, &starting_off)) {
485 SLOGE("Unable to get crypt_ftr_info\n");
486 return -1;
487 }
488 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700489 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700490 return -1;
491 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700492 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700493 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700494 return -1;
495 }
496
497 /* Seek to the start of the crypt footer */
498 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
499 SLOGE("Cannot seek to real block device footer\n");
500 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800501 }
502
503 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
504 SLOGE("Cannot write real block device footer\n");
505 goto errout;
506 }
507
Ken Sumrall3be890f2011-09-14 16:53:46 -0700508 fstat(fd, &statbuf);
509 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700510 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700511 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800512 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800513 goto errout;
514 }
515 }
516
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800517 /* Success! */
518 rc = 0;
519
520errout:
521 close(fd);
522 return rc;
523
524}
525
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800526static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr)
527{
528 struct crypt_mnt_ftr copy;
529 memcpy(&copy, crypt_ftr, sizeof(copy));
530 set_ftr_sha(&copy);
531 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
532}
533
Ken Sumrall160b4d62013-04-22 12:15:39 -0700534static inline int unix_read(int fd, void* buff, int len)
535{
536 return TEMP_FAILURE_RETRY(read(fd, buff, len));
537}
538
539static inline int unix_write(int fd, const void* buff, int len)
540{
541 return TEMP_FAILURE_RETRY(write(fd, buff, len));
542}
543
544static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
545{
546 memset(pdata, 0, len);
547 pdata->persist_magic = PERSIST_DATA_MAGIC;
548 pdata->persist_valid_entries = 0;
549}
550
551/* A routine to update the passed in crypt_ftr to the lastest version.
552 * fd is open read/write on the device that holds the crypto footer and persistent
553 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
554 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
555 */
556static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
557{
Kenny Root7434b312013-06-14 11:29:53 -0700558 int orig_major = crypt_ftr->major_version;
559 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700560
Kenny Root7434b312013-06-14 11:29:53 -0700561 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
562 struct crypt_persist_data *pdata;
563 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700564
Kenny Rootc4c70f12013-06-14 12:11:38 -0700565 SLOGW("upgrading crypto footer to 1.1");
566
Wei Wang4375f1b2017-02-24 17:43:01 -0800567 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700568 if (pdata == NULL) {
569 SLOGE("Cannot allocate persisent data\n");
570 return;
571 }
572 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
573
574 /* Need to initialize the persistent data area */
575 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
576 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100577 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700578 return;
579 }
580 /* Write all zeros to the first copy, making it invalid */
581 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
582
583 /* Write a valid but empty structure to the second copy */
584 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
585 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
586
587 /* Update the footer */
588 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
589 crypt_ftr->persist_data_offset[0] = pdata_offset;
590 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
591 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100592 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700593 }
594
Paul Lawrencef4faa572014-01-29 13:31:03 -0800595 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700596 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800597 /* But keep the old kdf_type.
598 * It will get updated later to KDF_SCRYPT after the password has been verified.
599 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700600 crypt_ftr->kdf_type = KDF_PBKDF2;
601 get_device_scrypt_params(crypt_ftr);
602 crypt_ftr->minor_version = 2;
603 }
604
Paul Lawrencef4faa572014-01-29 13:31:03 -0800605 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
606 SLOGW("upgrading crypto footer to 1.3");
607 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
608 crypt_ftr->minor_version = 3;
609 }
610
Kenny Root7434b312013-06-14 11:29:53 -0700611 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
612 if (lseek64(fd, offset, SEEK_SET) == -1) {
613 SLOGE("Cannot seek to crypt footer\n");
614 return;
615 }
616 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700617 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700618}
619
620
621static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800622{
623 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800624 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700625 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800626 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700627 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700628 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800629
Ken Sumrall160b4d62013-04-22 12:15:39 -0700630 if (get_crypt_ftr_info(&fname, &starting_off)) {
631 SLOGE("Unable to get crypt_ftr_info\n");
632 return -1;
633 }
634 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700635 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700636 return -1;
637 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700638 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700639 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700640 return -1;
641 }
642
643 /* Make sure it's 16 Kbytes in length */
644 fstat(fd, &statbuf);
645 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
646 SLOGE("footer file %s is not the expected size!\n", fname);
647 goto errout;
648 }
649
650 /* Seek to the start of the crypt footer */
651 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
652 SLOGE("Cannot seek to real block device footer\n");
653 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800654 }
655
656 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
657 SLOGE("Cannot read real block device footer\n");
658 goto errout;
659 }
660
661 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700662 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800663 goto errout;
664 }
665
Kenny Rootc96a5f82013-06-14 12:08:28 -0700666 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
667 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
668 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800669 goto errout;
670 }
671
Kenny Rootc96a5f82013-06-14 12:08:28 -0700672 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
673 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
674 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800675 }
676
Ken Sumrall160b4d62013-04-22 12:15:39 -0700677 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
678 * copy on disk before returning.
679 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700680 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700681 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800682 }
683
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800684 /* Success! */
685 rc = 0;
686
687errout:
688 close(fd);
689 return rc;
690}
691
Ken Sumrall160b4d62013-04-22 12:15:39 -0700692static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
693{
694 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
695 crypt_ftr->persist_data_offset[1]) {
696 SLOGE("Crypt_ftr persist data regions overlap");
697 return -1;
698 }
699
700 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
701 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
702 return -1;
703 }
704
705 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
706 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
707 CRYPT_FOOTER_OFFSET) {
708 SLOGE("Persistent data extends past crypto footer");
709 return -1;
710 }
711
712 return 0;
713}
714
715static int load_persistent_data(void)
716{
717 struct crypt_mnt_ftr crypt_ftr;
718 struct crypt_persist_data *pdata = NULL;
719 char encrypted_state[PROPERTY_VALUE_MAX];
720 char *fname;
721 int found = 0;
722 int fd;
723 int ret;
724 int i;
725
726 if (persist_data) {
727 /* Nothing to do, we've already loaded or initialized it */
728 return 0;
729 }
730
731
732 /* If not encrypted, just allocate an empty table and initialize it */
733 property_get("ro.crypto.state", encrypted_state, "");
734 if (strcmp(encrypted_state, "encrypted") ) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800735 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700736 if (pdata) {
737 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
738 persist_data = pdata;
739 return 0;
740 }
741 return -1;
742 }
743
744 if(get_crypt_ftr_and_key(&crypt_ftr)) {
745 return -1;
746 }
747
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700748 if ((crypt_ftr.major_version < 1)
749 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700750 SLOGE("Crypt_ftr version doesn't support persistent data");
751 return -1;
752 }
753
754 if (get_crypt_ftr_info(&fname, NULL)) {
755 return -1;
756 }
757
758 ret = validate_persistent_data_storage(&crypt_ftr);
759 if (ret) {
760 return -1;
761 }
762
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700763 fd = open(fname, O_RDONLY|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700764 if (fd < 0) {
765 SLOGE("Cannot open %s metadata file", fname);
766 return -1;
767 }
768
Wei Wang4375f1b2017-02-24 17:43:01 -0800769 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800770 if (pdata == NULL) {
771 SLOGE("Cannot allocate memory for persistent data");
772 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700773 }
774
775 for (i = 0; i < 2; i++) {
776 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
777 SLOGE("Cannot seek to read persistent data on %s", fname);
778 goto err2;
779 }
780 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
781 SLOGE("Error reading persistent data on iteration %d", i);
782 goto err2;
783 }
784 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
785 found = 1;
786 break;
787 }
788 }
789
790 if (!found) {
791 SLOGI("Could not find valid persistent data, creating");
792 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
793 }
794
795 /* Success */
796 persist_data = pdata;
797 close(fd);
798 return 0;
799
800err2:
801 free(pdata);
802
803err:
804 close(fd);
805 return -1;
806}
807
808static int save_persistent_data(void)
809{
810 struct crypt_mnt_ftr crypt_ftr;
811 struct crypt_persist_data *pdata;
812 char *fname;
813 off64_t write_offset;
814 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700815 int fd;
816 int ret;
817
818 if (persist_data == NULL) {
819 SLOGE("No persistent data to save");
820 return -1;
821 }
822
823 if(get_crypt_ftr_and_key(&crypt_ftr)) {
824 return -1;
825 }
826
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700827 if ((crypt_ftr.major_version < 1)
828 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700829 SLOGE("Crypt_ftr version doesn't support persistent data");
830 return -1;
831 }
832
833 ret = validate_persistent_data_storage(&crypt_ftr);
834 if (ret) {
835 return -1;
836 }
837
838 if (get_crypt_ftr_info(&fname, NULL)) {
839 return -1;
840 }
841
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700842 fd = open(fname, O_RDWR|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700843 if (fd < 0) {
844 SLOGE("Cannot open %s metadata file", fname);
845 return -1;
846 }
847
Wei Wang4375f1b2017-02-24 17:43:01 -0800848 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700849 if (pdata == NULL) {
850 SLOGE("Cannot allocate persistant data");
851 goto err;
852 }
853
854 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
855 SLOGE("Cannot seek to read persistent data on %s", fname);
856 goto err2;
857 }
858
859 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
860 SLOGE("Error reading persistent data before save");
861 goto err2;
862 }
863
864 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
865 /* The first copy is the curent valid copy, so write to
866 * the second copy and erase this one */
867 write_offset = crypt_ftr.persist_data_offset[1];
868 erase_offset = crypt_ftr.persist_data_offset[0];
869 } else {
870 /* The second copy must be the valid copy, so write to
871 * the first copy, and erase the second */
872 write_offset = crypt_ftr.persist_data_offset[0];
873 erase_offset = crypt_ftr.persist_data_offset[1];
874 }
875
876 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100877 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700878 SLOGE("Cannot seek to write persistent data");
879 goto err2;
880 }
881 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
882 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100883 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700884 SLOGE("Cannot seek to erase previous persistent data");
885 goto err2;
886 }
887 fsync(fd);
888 memset(pdata, 0, crypt_ftr.persist_data_size);
889 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
890 (int) crypt_ftr.persist_data_size) {
891 SLOGE("Cannot write to erase previous persistent data");
892 goto err2;
893 }
894 fsync(fd);
895 } else {
896 SLOGE("Cannot write to save persistent data");
897 goto err2;
898 }
899
900 /* Success */
901 free(pdata);
902 close(fd);
903 return 0;
904
905err2:
906 free(pdata);
907err:
908 close(fd);
909 return -1;
910}
911
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800912/* Convert a binary key of specified length into an ascii hex string equivalent,
913 * without the leading 0x and with null termination
914 */
Jeff Sharkey9c484982015-03-31 10:35:33 -0700915static void convert_key_to_hex_ascii(const unsigned char *master_key,
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700916 unsigned int keysize, char *master_key_ascii) {
917 unsigned int i, a;
918 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800919
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700920 for (i=0, a=0; i<keysize; i++, a+=2) {
921 /* For each byte, write out two ascii hex digits */
922 nibble = (master_key[i] >> 4) & 0xf;
923 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800924
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700925 nibble = master_key[i] & 0xf;
926 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
927 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800928
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700929 /* Add the null termination */
930 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800931
932}
933
Jeff Sharkey9c484982015-03-31 10:35:33 -0700934static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
935 const unsigned char *master_key, const char *real_blk_name,
936 const char *name, int fd, const char *extra_params) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800937 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800938 struct dm_ioctl *io;
939 struct dm_target_spec *tgt;
940 char *crypt_params;
Greg Kaiser291fec12018-02-09 18:24:59 -0800941 // We can't assume the key is only get_keysize(). But we do know its limit
Greg Kaiser1452b272018-02-09 16:11:38 -0800942 // due to the crypt_mnt_ftr struct. We need two ASCII characters to represent
943 // each byte, and need space for the '\0' terminator.
944 char master_key_ascii[sizeof(crypt_ftr->master_key) * 2 + 1];
George Burgess IV605d7ae2016-02-29 13:39:17 -0800945 size_t buff_offset;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800946 int i;
947
948 io = (struct dm_ioctl *) buffer;
949
950 /* Load the mapping table for this device */
951 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
952
953 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
954 io->target_count = 1;
955 tgt->status = 0;
956 tgt->sector_start = 0;
957 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -0700958 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800959
960 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
961 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800962
963 buff_offset = crypt_params - buffer;
Paul Crowley5afbc622017-11-27 09:42:17 -0800964 SLOGI("Extra parameters for dm_crypt: %s\n", extra_params);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800965 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
966 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name,
967 extra_params);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800968 crypt_params += strlen(crypt_params) + 1;
969 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
970 tgt->next = crypt_params - buffer;
971
972 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
973 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
974 break;
975 }
976 usleep(500000);
977 }
978
979 if (i == TABLE_LOAD_RETRIES) {
980 /* We failed to load the table, return an error */
981 return -1;
982 } else {
983 return i + 1;
984 }
985}
986
987
988static int get_dm_crypt_version(int fd, const char *name, int *version)
989{
990 char buffer[DM_CRYPT_BUF_SIZE];
991 struct dm_ioctl *io;
992 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800993
994 io = (struct dm_ioctl *) buffer;
995
996 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
997
998 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
999 return -1;
1000 }
1001
1002 /* Iterate over the returned versions, looking for name of "crypt".
1003 * When found, get and return the version.
1004 */
1005 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1006 while (v->next) {
1007 if (! strcmp(v->name, "crypt")) {
1008 /* We found the crypt driver, return the version, and get out */
1009 version[0] = v->version[0];
1010 version[1] = v->version[1];
1011 version[2] = v->version[2];
1012 return 0;
1013 }
1014 v = (struct dm_target_versions *)(((char *)v) + v->next);
1015 }
1016
1017 return -1;
1018}
1019
Paul Crowley5afbc622017-11-27 09:42:17 -08001020static std::string extra_params_as_string(const std::vector<std::string>& extra_params_vec) {
1021 if (extra_params_vec.empty()) return "";
1022 std::string extra_params = std::to_string(extra_params_vec.size());
1023 for (const auto& p : extra_params_vec) {
1024 extra_params.append(" ");
1025 extra_params.append(p);
1026 }
1027 return extra_params;
1028}
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001029
Paul Crowley5afbc622017-11-27 09:42:17 -08001030static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
1031 const char* real_blk_name, char* crypto_blk_name, const char* name,
1032 uint32_t flags) {
1033 char buffer[DM_CRYPT_BUF_SIZE];
1034 struct dm_ioctl* io;
1035 unsigned int minor;
1036 int fd = 0;
1037 int err;
1038 int retval = -1;
1039 int version[3];
1040 int load_count;
1041 std::vector<std::string> extra_params_vec;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001042
Paul Crowley5afbc622017-11-27 09:42:17 -08001043 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1044 SLOGE("Cannot open device-mapper\n");
1045 goto errout;
1046 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001047
Paul Crowley5afbc622017-11-27 09:42:17 -08001048 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001049
Paul Crowley5afbc622017-11-27 09:42:17 -08001050 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1051 err = ioctl(fd, DM_DEV_CREATE, io);
1052 if (err) {
1053 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
1054 goto errout;
1055 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001056
Paul Crowley5afbc622017-11-27 09:42:17 -08001057 /* Get the device status, in particular, the name of it's device file */
1058 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1059 if (ioctl(fd, DM_DEV_STATUS, io)) {
1060 SLOGE("Cannot retrieve dm-crypt device status\n");
1061 goto errout;
1062 }
1063 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1064 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
Ken Sumralle919efe2012-09-29 17:07:41 -07001065
Paul Crowley5afbc622017-11-27 09:42:17 -08001066 if (!get_dm_crypt_version(fd, name, version)) {
1067 /* Support for allow_discards was added in version 1.11.0 */
1068 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
1069 extra_params_vec.emplace_back("allow_discards");
1070 }
1071 }
1072 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
1073 extra_params_vec.emplace_back("allow_encrypt_override");
1074 }
1075 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1076 extra_params_as_string(extra_params_vec).c_str());
1077 if (load_count < 0) {
1078 SLOGE("Cannot load dm-crypt mapping table.\n");
1079 goto errout;
1080 } else if (load_count > 1) {
1081 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1082 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001083
Paul Crowley5afbc622017-11-27 09:42:17 -08001084 /* Resume this device to activate it */
1085 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001086
Paul Crowley5afbc622017-11-27 09:42:17 -08001087 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1088 SLOGE("Cannot resume the dm-crypt device\n");
1089 goto errout;
1090 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001091
Paul Crowley5afbc622017-11-27 09:42:17 -08001092 /* We made it here with no errors. Woot! */
1093 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001094
1095errout:
1096 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1097
1098 return retval;
1099}
1100
Wei Wang4375f1b2017-02-24 17:43:01 -08001101static int delete_crypto_blk_dev(const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001102{
1103 int fd;
1104 char buffer[DM_CRYPT_BUF_SIZE];
1105 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001106 int retval = -1;
1107
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001108 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001109 SLOGE("Cannot open device-mapper\n");
1110 goto errout;
1111 }
1112
1113 io = (struct dm_ioctl *) buffer;
1114
1115 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1116 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1117 SLOGE("Cannot remove dm-crypt device\n");
1118 goto errout;
1119 }
1120
1121 /* We made it here with no errors. Woot! */
1122 retval = 0;
1123
1124errout:
1125 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1126
1127 return retval;
1128
1129}
1130
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001131static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001132 unsigned char *ikey, void *params UNUSED)
1133{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001134 SLOGI("Using pbkdf2 for cryptfs KDF");
1135
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001136 /* Turn the password into a key and IV that can decrypt the master key */
Adam Langleybf0d9722015-11-04 14:51:39 -08001137 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
Greg Kaiser291fec12018-02-09 18:24:59 -08001138 HASH_COUNT, get_keysize() + IV_LEN_BYTES,
Adam Langleybf0d9722015-11-04 14:51:39 -08001139 ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001140}
1141
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001142static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001143 unsigned char *ikey, void *params)
1144{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001145 SLOGI("Using scrypt for cryptfs KDF");
1146
Kenny Rootc4c70f12013-06-14 12:11:38 -07001147 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1148
1149 int N = 1 << ftr->N_factor;
1150 int r = 1 << ftr->r_factor;
1151 int p = 1 << ftr->p_factor;
1152
1153 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001154 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1155 salt, SALT_LEN, N, r, p, ikey,
Greg Kaiser291fec12018-02-09 18:24:59 -08001156 get_keysize() + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001157
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001158 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001159}
1160
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001161static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1162 unsigned char *ikey, void *params)
1163{
1164 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1165
1166 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001167 size_t signature_size;
1168 unsigned char* signature;
1169 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1170
1171 int N = 1 << ftr->N_factor;
1172 int r = 1 << ftr->r_factor;
1173 int p = 1 << ftr->p_factor;
1174
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001175 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1176 salt, SALT_LEN, N, r, p, ikey,
Greg Kaiser291fec12018-02-09 18:24:59 -08001177 get_keysize() + IV_LEN_BYTES);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001178
1179 if (rc) {
1180 SLOGE("scrypt failed");
1181 return -1;
1182 }
1183
Greg Kaiser291fec12018-02-09 18:24:59 -08001184 if (keymaster_sign_object(ftr, ikey, get_keysize() + IV_LEN_BYTES,
Shawn Willdene17a9c42014-09-08 13:04:08 -06001185 &signature, &signature_size)) {
1186 SLOGE("Signing failed");
1187 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001188 }
1189
1190 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
Greg Kaiser291fec12018-02-09 18:24:59 -08001191 N, r, p, ikey, get_keysize() + IV_LEN_BYTES);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001192 free(signature);
1193
1194 if (rc) {
1195 SLOGE("scrypt failed");
1196 return -1;
1197 }
1198
1199 return 0;
1200}
1201
1202static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1203 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001204 unsigned char *encrypted_master_key,
1205 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001206{
Greg Kaiser291fec12018-02-09 18:24:59 -08001207 unsigned char ikey[MAX_KEY_LEN+IV_LEN_BYTES] = { 0 };
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001208 EVP_CIPHER_CTX e_ctx;
1209 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001210 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001211
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001212 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001213 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001214
1215 switch (crypt_ftr->kdf_type) {
1216 case KDF_SCRYPT_KEYMASTER:
1217 if (keymaster_create_key(crypt_ftr)) {
1218 SLOGE("keymaster_create_key failed");
1219 return -1;
1220 }
1221
1222 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1223 SLOGE("scrypt failed");
1224 return -1;
1225 }
1226 break;
1227
1228 case KDF_SCRYPT:
1229 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1230 SLOGE("scrypt failed");
1231 return -1;
1232 }
1233 break;
1234
1235 default:
1236 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001237 return -1;
1238 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001239
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001240 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001241 EVP_CIPHER_CTX_init(&e_ctx);
Greg Kaiser291fec12018-02-09 18:24:59 -08001242 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+get_keysize())) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001243 SLOGE("EVP_EncryptInit failed\n");
1244 return -1;
1245 }
1246 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001247
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001248 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001249 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Greg Kaiser291fec12018-02-09 18:24:59 -08001250 decrypted_master_key, get_keysize())) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001251 SLOGE("EVP_EncryptUpdate failed\n");
1252 return -1;
1253 }
Adam Langley889c4f12014-09-03 14:23:13 -07001254 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001255 SLOGE("EVP_EncryptFinal failed\n");
1256 return -1;
1257 }
1258
Greg Kaiser291fec12018-02-09 18:24:59 -08001259 if (encrypted_len + final_len != static_cast<int>(get_keysize())) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001260 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1261 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001262 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001263
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001264 /* Store the scrypt of the intermediate key, so we can validate if it's a
1265 password error or mount error when things go wrong.
1266 Note there's no need to check for errors, since if this is incorrect, we
1267 simply won't wipe userdata, which is the correct default behavior
1268 */
1269 int N = 1 << crypt_ftr->N_factor;
1270 int r = 1 << crypt_ftr->r_factor;
1271 int p = 1 << crypt_ftr->p_factor;
1272
Greg Kaiser291fec12018-02-09 18:24:59 -08001273 rc = crypto_scrypt(ikey, get_keysize(),
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001274 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1275 crypt_ftr->scrypted_intermediate_key,
1276 sizeof(crypt_ftr->scrypted_intermediate_key));
1277
1278 if (rc) {
1279 SLOGE("encrypt_master_key: crypto_scrypt failed");
1280 }
1281
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001282 EVP_CIPHER_CTX_cleanup(&e_ctx);
1283
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001284 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001285}
1286
Paul Lawrence731a7a22015-04-28 22:14:15 +00001287static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001288 unsigned char *encrypted_master_key,
1289 unsigned char *decrypted_master_key,
1290 kdf_func kdf, void *kdf_params,
1291 unsigned char** intermediate_key,
1292 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001293{
Greg Kaiser291fec12018-02-09 18:24:59 -08001294 unsigned char ikey[MAX_KEY_LEN+IV_LEN_BYTES] = { 0 };
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001295 EVP_CIPHER_CTX d_ctx;
1296 int decrypted_len, final_len;
1297
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001298 /* Turn the password into an intermediate key and IV that can decrypt the
1299 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001300 if (kdf(passwd, salt, ikey, kdf_params)) {
1301 SLOGE("kdf failed");
1302 return -1;
1303 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001304
1305 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001306 EVP_CIPHER_CTX_init(&d_ctx);
Greg Kaiser291fec12018-02-09 18:24:59 -08001307 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+get_keysize())) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001308 return -1;
1309 }
1310 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1311 /* Decrypt the master key */
1312 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
Greg Kaiser291fec12018-02-09 18:24:59 -08001313 encrypted_master_key, get_keysize())) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001314 return -1;
1315 }
Adam Langley889c4f12014-09-03 14:23:13 -07001316 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001317 return -1;
1318 }
1319
Greg Kaiser291fec12018-02-09 18:24:59 -08001320 if (decrypted_len + final_len != static_cast<int>(get_keysize())) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001321 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001322 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001323
1324 /* Copy intermediate key if needed by params */
1325 if (intermediate_key && intermediate_key_size) {
Greg Kaiser291fec12018-02-09 18:24:59 -08001326 *intermediate_key = (unsigned char*) malloc(get_keysize());
Greg Kaisere8167af2016-04-20 10:50:15 -07001327 if (*intermediate_key) {
Greg Kaiser291fec12018-02-09 18:24:59 -08001328 memcpy(*intermediate_key, ikey, get_keysize());
1329 *intermediate_key_size = get_keysize();
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001330 }
1331 }
1332
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001333 EVP_CIPHER_CTX_cleanup(&d_ctx);
1334
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001335 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001336}
1337
Kenny Rootc4c70f12013-06-14 12:11:38 -07001338static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001339{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001340 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001341 *kdf = scrypt_keymaster;
1342 *kdf_params = ftr;
1343 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001344 *kdf = scrypt;
1345 *kdf_params = ftr;
1346 } else {
1347 *kdf = pbkdf2;
1348 *kdf_params = NULL;
1349 }
1350}
1351
Paul Lawrence731a7a22015-04-28 22:14:15 +00001352static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001353 struct crypt_mnt_ftr *crypt_ftr,
1354 unsigned char** intermediate_key,
1355 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001356{
1357 kdf_func kdf;
1358 void *kdf_params;
1359 int ret;
1360
1361 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001362 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1363 decrypted_master_key, kdf, kdf_params,
1364 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001365 if (ret != 0) {
1366 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001367 }
1368
1369 return ret;
1370}
1371
Wei Wang4375f1b2017-02-24 17:43:01 -08001372static int create_encrypted_random_key(const char *passwd, unsigned char *master_key, unsigned char *salt,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001373 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001374 int fd;
Greg Kaiser291fec12018-02-09 18:24:59 -08001375 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001376
1377 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001378 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001379 read(fd, key_buf, sizeof(key_buf));
1380 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001381 close(fd);
1382
1383 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001384 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001385}
1386
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001387int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001388{
Greg Hackmann955653e2014-09-24 14:55:20 -07001389 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001390#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001391
1392 /* Now umount the tmpfs filesystem */
1393 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001394 if (umount(mountpoint) == 0) {
1395 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001396 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001397
1398 if (errno == EINVAL) {
1399 /* EINVAL is returned if the directory is not a mountpoint,
1400 * i.e. there is no filesystem mounted there. So just get out.
1401 */
1402 break;
1403 }
1404
1405 err = errno;
1406
1407 /* If allowed, be increasingly aggressive before the last two retries */
1408 if (kill) {
1409 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1410 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001411 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001412 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1413 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001414 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001415 }
1416 }
1417
1418 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001419 }
1420
1421 if (i < WAIT_UNMOUNT_COUNT) {
1422 SLOGD("unmounting %s succeeded\n", mountpoint);
1423 rc = 0;
1424 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001425 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001426 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001427 rc = -1;
1428 }
1429
1430 return rc;
1431}
1432
Wei Wang42e38102017-06-07 10:46:12 -07001433static void prep_data_fs(void)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001434{
Jeff Sharkey47695b22016-02-01 17:02:29 -07001435 // NOTE: post_fs_data results in init calling back around to vold, so all
1436 // callers to this method must be async
1437
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001438 /* Do the prep of the /data filesystem */
1439 property_set("vold.post_fs_data_done", "0");
1440 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001441 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001442
Ken Sumrallc5872692013-05-14 15:26:31 -07001443 /* Wait a max of 50 seconds, hopefully it takes much less */
Wei Wang42e38102017-06-07 10:46:12 -07001444 while (!android::base::WaitForProperty("vold.post_fs_data_done",
Wei Wang4375f1b2017-02-24 17:43:01 -08001445 "1",
Wei Wang42e38102017-06-07 10:46:12 -07001446 std::chrono::seconds(15))) {
1447 /* We timed out to prep /data in time. Continue wait. */
1448 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001449 }
Wei Wang42e38102017-06-07 10:46:12 -07001450 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001451}
1452
Paul Lawrence74f29f12014-08-28 15:54:10 -07001453static void cryptfs_set_corrupt()
1454{
1455 // Mark the footer as bad
1456 struct crypt_mnt_ftr crypt_ftr;
1457 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1458 SLOGE("Failed to get crypto footer - panic");
1459 return;
1460 }
1461
1462 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1463 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1464 SLOGE("Failed to set crypto footer - panic");
1465 return;
1466 }
1467}
1468
1469static void cryptfs_trigger_restart_min_framework()
1470{
1471 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1472 SLOGE("Failed to mount tmpfs on data - panic");
1473 return;
1474 }
1475
1476 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1477 SLOGE("Failed to trigger post fs data - panic");
1478 return;
1479 }
1480
1481 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1482 SLOGE("Failed to trigger restart min framework - panic");
1483 return;
1484 }
1485}
1486
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001487/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001488static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001489{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001490 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001491 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001492 static int restart_successful = 0;
1493
1494 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001495 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001496 SLOGE("Encrypted filesystem not validated, aborting");
1497 return -1;
1498 }
1499
1500 if (restart_successful) {
1501 SLOGE("System already restarted with encrypted disk, aborting");
1502 return -1;
1503 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001504
Paul Lawrencef4faa572014-01-29 13:31:03 -08001505 if (restart_main) {
1506 /* Here is where we shut down the framework. The init scripts
1507 * start all services in one of three classes: core, main or late_start.
1508 * On boot, we start core and main. Now, we stop main, but not core,
1509 * as core includes vold and a few other really important things that
1510 * we need to keep running. Once main has stopped, we should be able
1511 * to umount the tmpfs /data, then mount the encrypted /data.
1512 * We then restart the class main, and also the class late_start.
1513 * At the moment, I've only put a few things in late_start that I know
1514 * are not needed to bring up the framework, and that also cause problems
1515 * with unmounting the tmpfs /data, but I hope to add add more services
1516 * to the late_start class as we optimize this to decrease the delay
1517 * till the user is asked for the password to the filesystem.
1518 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001519
Paul Lawrencef4faa572014-01-29 13:31:03 -08001520 /* The init files are setup to stop the class main when vold.decrypt is
1521 * set to trigger_reset_main.
1522 */
1523 property_set("vold.decrypt", "trigger_reset_main");
1524 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001525
Paul Lawrencef4faa572014-01-29 13:31:03 -08001526 /* Ugh, shutting down the framework is not synchronous, so until it
1527 * can be fixed, this horrible hack will wait a moment for it all to
1528 * shut down before proceeding. Without it, some devices cannot
1529 * restart the graphics services.
1530 */
1531 sleep(2);
1532 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001533
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001534 /* Now that the framework is shutdown, we should be able to umount()
1535 * the tmpfs filesystem, and mount the real one.
1536 */
1537
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001538 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1539 if (strlen(crypto_blkdev) == 0) {
1540 SLOGE("fs_crypto_blkdev not set\n");
1541 return -1;
1542 }
1543
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001544 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001545 /* If ro.crypto.readonly is set to 1, mount the decrypted
1546 * filesystem readonly. This is used when /data is mounted by
1547 * recovery mode.
1548 */
1549 char ro_prop[PROPERTY_VALUE_MAX];
1550 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001551 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001552 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Doug Zongker6fd57712013-12-17 09:43:23 -08001553 rec->flags |= MS_RDONLY;
1554 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001555
Ken Sumralle5032c42012-04-01 23:58:44 -07001556 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001557 int retries = RETRY_MOUNT_ATTEMPTS;
1558 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001559
1560 /*
1561 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1562 * partitions in the fsck domain.
1563 */
1564 if (setexeccon(secontextFsck())){
1565 SLOGE("Failed to setexeccon");
1566 return -1;
1567 }
Paul Crowleye2ee1522017-09-26 14:05:26 -07001568 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT,
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001569 crypto_blkdev, 0))
1570 != 0) {
1571 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1572 /* TODO: invoke something similar to
1573 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1574 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1575 SLOGI("Failed to mount %s because it is busy - waiting",
1576 crypto_blkdev);
1577 if (--retries) {
1578 sleep(RETRY_MOUNT_DELAY_SECONDS);
1579 } else {
1580 /* Let's hope that a reboot clears away whatever is keeping
1581 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001582 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001583 }
1584 } else {
1585 SLOGE("Failed to mount decrypted data");
1586 cryptfs_set_corrupt();
1587 cryptfs_trigger_restart_min_framework();
1588 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001589 if (setexeccon(NULL)) {
1590 SLOGE("Failed to setexeccon");
1591 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001592 return -1;
1593 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001594 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001595 if (setexeccon(NULL)) {
1596 SLOGE("Failed to setexeccon");
1597 return -1;
1598 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001599
Ken Sumralle5032c42012-04-01 23:58:44 -07001600 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001601 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001602 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001603
1604 /* startup service classes main and late_start */
1605 property_set("vold.decrypt", "trigger_restart_framework");
1606 SLOGD("Just triggered restart_framework\n");
1607
1608 /* Give it a few moments to get started */
1609 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001610 }
1611
Ken Sumrall0cc16632011-01-18 20:32:26 -08001612 if (rc == 0) {
1613 restart_successful = 1;
1614 }
1615
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001616 return rc;
1617}
1618
Paul Lawrencef4faa572014-01-29 13:31:03 -08001619int cryptfs_restart(void)
1620{
Paul Lawrence05335c32015-03-05 09:46:23 -08001621 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001622 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001623 SLOGE("cryptfs_restart not valid for file encryption:");
1624 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001625 }
1626
Paul Lawrencef4faa572014-01-29 13:31:03 -08001627 /* Call internal implementation forcing a restart of main service group */
1628 return cryptfs_restart_internal(1);
1629}
1630
Wei Wang4375f1b2017-02-24 17:43:01 -08001631static int do_crypto_complete(const char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001632{
1633 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001634 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001635 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001636
1637 property_get("ro.crypto.state", encrypted_state, "");
1638 if (strcmp(encrypted_state, "encrypted") ) {
1639 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001640 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001641 }
1642
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001643 // crypto_complete is full disk encrypted status
Paul Crowley38132a12016-02-09 09:50:32 +00001644 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001645 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Paul Lawrence05335c32015-03-05 09:46:23 -08001646 }
1647
Ken Sumrall160b4d62013-04-22 12:15:39 -07001648 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001649 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001650
Ken Sumralle1a45852011-12-14 21:24:27 -08001651 /*
1652 * Only report this error if key_loc is a file and it exists.
1653 * If the device was never encrypted, and /data is not mountable for
1654 * some reason, returning 1 should prevent the UI from presenting the
1655 * a "enter password" screen, or worse, a "press button to wipe the
1656 * device" screen.
1657 */
1658 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1659 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001660 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001661 } else {
1662 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001663 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001664 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001665 }
1666
Paul Lawrence74f29f12014-08-28 15:54:10 -07001667 // Test for possible error flags
1668 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1669 SLOGE("Encryption process is partway completed\n");
1670 return CRYPTO_COMPLETE_PARTIAL;
1671 }
1672
1673 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1674 SLOGE("Encryption process was interrupted but cannot continue\n");
1675 return CRYPTO_COMPLETE_INCONSISTENT;
1676 }
1677
1678 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1679 SLOGE("Encryption is successful but data is corrupt\n");
1680 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001681 }
1682
1683 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001684 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001685}
1686
Paul Lawrencef4faa572014-01-29 13:31:03 -08001687static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
Wei Wang4375f1b2017-02-24 17:43:01 -08001688 const char *passwd, const char *mount_point, const char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001689{
Greg Kaiser4a35ef02018-02-09 17:01:06 -08001690 unsigned char decrypted_master_key[DECRYPTED_MASTER_KEY_BUF_SIZE];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001691 char crypto_blkdev[MAXPATHLEN];
1692 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001693 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001694 unsigned int orig_failed_decrypt_count;
1695 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001696 int use_keymaster = 0;
1697 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001698 unsigned char* intermediate_key = 0;
1699 size_t intermediate_key_size = 0;
Wei Wang4375f1b2017-02-24 17:43:01 -08001700 int N = 1 << crypt_ftr->N_factor;
1701 int r = 1 << crypt_ftr->r_factor;
1702 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001703
Paul Lawrencef4faa572014-01-29 13:31:03 -08001704 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1705 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001706
Paul Lawrencef4faa572014-01-29 13:31:03 -08001707 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001708 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1709 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001710 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001711 rc = -1;
1712 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001713 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001714 }
1715
Paul Crowleye2ee1522017-09-26 14:05:26 -07001716 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Paul Lawrencef4faa572014-01-29 13:31:03 -08001717
Paul Lawrence74f29f12014-08-28 15:54:10 -07001718 // Create crypto block device - all (non fatal) code paths
1719 // need it
Paul Crowley5afbc622017-11-27 09:42:17 -08001720 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label, 0)) {
1721 SLOGE("Error creating decrypted block device\n");
1722 rc = -1;
1723 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001724 }
1725
Paul Lawrence74f29f12014-08-28 15:54:10 -07001726 /* Work out if the problem is the password or the data */
1727 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1728 scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001729
Paul Lawrence74f29f12014-08-28 15:54:10 -07001730 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1731 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1732 N, r, p, scrypted_intermediate_key,
1733 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001734
Paul Lawrence74f29f12014-08-28 15:54:10 -07001735 // Does the key match the crypto footer?
1736 if (rc == 0 && memcmp(scrypted_intermediate_key,
1737 crypt_ftr->scrypted_intermediate_key,
1738 sizeof(scrypted_intermediate_key)) == 0) {
1739 SLOGI("Password matches");
1740 rc = 0;
1741 } else {
1742 /* Try mounting the file system anyway, just in case the problem's with
1743 * the footer, not the key. */
George Burgess IV605d7ae2016-02-29 13:39:17 -08001744 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt",
1745 mount_point);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001746 mkdir(tmp_mount_point, 0755);
Paul Crowleye2ee1522017-09-26 14:05:26 -07001747 if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001748 SLOGE("Error temp mounting decrypted block device\n");
1749 delete_crypto_blk_dev(label);
1750
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001751 rc = ++crypt_ftr->failed_decrypt_count;
1752 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001753 } else {
1754 /* Success! */
1755 SLOGI("Password did not match but decrypted drive mounted - continue");
1756 umount(tmp_mount_point);
1757 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001758 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001759 }
1760
1761 if (rc == 0) {
1762 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001763 if (orig_failed_decrypt_count != 0) {
1764 put_crypt_ftr_and_key(crypt_ftr);
1765 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001766
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001767 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001768 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001769 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001770
1771 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001772 * the key when we want to change the password on it. */
Greg Kaiser291fec12018-02-09 18:24:59 -08001773 memcpy(saved_master_key, decrypted_master_key, get_keysize());
Ken Sumrall3ad90722011-10-04 20:38:29 -07001774 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001775 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001776 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001777 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001778
Paul Lawrence74f29f12014-08-28 15:54:10 -07001779 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001780 use_keymaster = keymaster_check_compatibility();
1781 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001782 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001783 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1784 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1785 upgrade = 1;
1786 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001787 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001788 upgrade = 1;
1789 }
1790
1791 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001792 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1793 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001794 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001795 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001796 }
1797 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001798
1799 // Do not fail even if upgrade failed - machine is bootable
1800 // Note that if this code is ever hit, there is a *serious* problem
1801 // since KDFs should never fail. You *must* fix the kdf before
1802 // proceeding!
1803 if (rc) {
1804 SLOGW("Upgrade failed with error %d,"
1805 " but continuing with previous state",
1806 rc);
1807 rc = 0;
1808 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001809 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001810 }
1811
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001812 errout:
1813 if (intermediate_key) {
1814 memset(intermediate_key, 0, intermediate_key_size);
1815 free(intermediate_key);
1816 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001817 return rc;
1818}
1819
Ken Sumrall29d8da82011-05-18 17:20:07 -07001820/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001821 * Called by vold when it's asked to mount an encrypted external
1822 * storage volume. The incoming partition has no crypto header/footer,
1823 * as any metadata is been stored in a separate, small partition.
1824 *
1825 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001826 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001827int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1828 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001829 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001830 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001831 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001832 return -1;
1833 }
1834
1835 unsigned long nr_sec = 0;
1836 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001837 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001838
Ken Sumrall29d8da82011-05-18 17:20:07 -07001839 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001840 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001841 return -1;
1842 }
1843
Jeff Sharkey9c484982015-03-31 10:35:33 -07001844 struct crypt_mnt_ftr ext_crypt_ftr;
1845 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1846 ext_crypt_ftr.fs_size = nr_sec;
1847 ext_crypt_ftr.keysize = keysize;
Greg Kaiser291fec12018-02-09 18:24:59 -08001848 strlcpy((char*) ext_crypt_ftr.crypto_type_name, get_crypt_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001849 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001850
Paul Crowley5afbc622017-11-27 09:42:17 -08001851 return create_crypto_blk_dev(
1852 &ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label,
1853 e4crypt_is_native() ? CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE : 0);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001854}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001855
Jeff Sharkey9c484982015-03-31 10:35:33 -07001856/*
1857 * Called by vold when it's asked to unmount an encrypted external
1858 * storage volume.
1859 */
1860int cryptfs_revert_ext_volume(const char* label) {
1861 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001862}
1863
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001864int cryptfs_crypto_complete(void)
1865{
1866 return do_crypto_complete("/data");
1867}
1868
Paul Lawrencef4faa572014-01-29 13:31:03 -08001869int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1870{
1871 char encrypted_state[PROPERTY_VALUE_MAX];
1872 property_get("ro.crypto.state", encrypted_state, "");
1873 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1874 SLOGE("encrypted fs already validated or not running with encryption,"
1875 " aborting");
1876 return -1;
1877 }
1878
1879 if (get_crypt_ftr_and_key(crypt_ftr)) {
1880 SLOGE("Error getting crypt footer and key");
1881 return -1;
1882 }
1883
1884 return 0;
1885}
1886
Wei Wang4375f1b2017-02-24 17:43:01 -08001887int cryptfs_check_passwd(const char *passwd)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001888{
Paul Lawrence05335c32015-03-05 09:46:23 -08001889 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00001890 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001891 SLOGE("cryptfs_check_passwd not valid for file encryption");
1892 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001893 }
1894
Paul Lawrencef4faa572014-01-29 13:31:03 -08001895 struct crypt_mnt_ftr crypt_ftr;
1896 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001897
Paul Lawrencef4faa572014-01-29 13:31:03 -08001898 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001899 if (rc) {
1900 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001901 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001902 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001903
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001904 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001905 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1906 if (rc) {
1907 SLOGE("Password did not match");
1908 return rc;
1909 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001910
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001911 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1912 // Here we have a default actual password but a real password
1913 // we must test against the scrypted value
1914 // First, we must delete the crypto block device that
1915 // test_mount_encrypted_fs leaves behind as a side effect
1916 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
1917 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
1918 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1919 if (rc) {
1920 SLOGE("Default password did not match on reboot encryption");
1921 return rc;
1922 }
1923
1924 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1925 put_crypt_ftr_and_key(&crypt_ftr);
1926 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1927 if (rc) {
1928 SLOGE("Could not change password on reboot encryption");
1929 return rc;
1930 }
1931 }
1932
1933 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001934 cryptfs_clear_password();
1935 password = strdup(passwd);
1936 struct timespec now;
1937 clock_gettime(CLOCK_BOOTTIME, &now);
1938 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001939 }
1940
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001941 return rc;
1942}
1943
Jeff Sharkey83b559c2017-09-12 16:30:52 -06001944int cryptfs_verify_passwd(const char *passwd)
Ken Sumrall3ad90722011-10-04 20:38:29 -07001945{
1946 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser4a35ef02018-02-09 17:01:06 -08001947 unsigned char decrypted_master_key[DECRYPTED_MASTER_KEY_BUF_SIZE];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001948 char encrypted_state[PROPERTY_VALUE_MAX];
1949 int rc;
1950
1951 property_get("ro.crypto.state", encrypted_state, "");
1952 if (strcmp(encrypted_state, "encrypted") ) {
1953 SLOGE("device not encrypted, aborting");
1954 return -2;
1955 }
1956
1957 if (!master_key_saved) {
1958 SLOGE("encrypted fs not yet mounted, aborting");
1959 return -1;
1960 }
1961
1962 if (!saved_mount_point) {
1963 SLOGE("encrypted fs failed to save mount point, aborting");
1964 return -1;
1965 }
1966
Ken Sumrall160b4d62013-04-22 12:15:39 -07001967 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001968 SLOGE("Error getting crypt footer and key\n");
1969 return -1;
1970 }
1971
1972 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1973 /* If the device has no password, then just say the password is valid */
1974 rc = 0;
1975 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001976 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001977 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1978 /* They match, the password is correct */
1979 rc = 0;
1980 } else {
1981 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1982 sleep(1);
1983 rc = 1;
1984 }
1985 }
1986
1987 return rc;
1988}
1989
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001990/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser291fec12018-02-09 18:24:59 -08001991 * defaulted to get_keysize(), and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001992 * Presumably, at a minimum, the caller will update the
1993 * filesystem size and crypto_type_name after calling this function.
1994 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001995static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001996{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001997 off64_t off;
1998
1999 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002000 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002001 ftr->major_version = CURRENT_MAJOR_VERSION;
2002 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002003 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser291fec12018-02-09 18:24:59 -08002004 ftr->keysize = get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07002005
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002006 switch (keymaster_check_compatibility()) {
2007 case 1:
2008 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2009 break;
2010
2011 case 0:
2012 ftr->kdf_type = KDF_SCRYPT;
2013 break;
2014
2015 default:
2016 SLOGE("keymaster_check_compatibility failed");
2017 return -1;
2018 }
2019
Kenny Rootc4c70f12013-06-14 12:11:38 -07002020 get_device_scrypt_params(ftr);
2021
Ken Sumrall160b4d62013-04-22 12:15:39 -07002022 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2023 if (get_crypt_ftr_info(NULL, &off) == 0) {
2024 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
2025 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
2026 ftr->persist_data_size;
2027 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002028
2029 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002030}
2031
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002032#define FRAMEWORK_BOOT_WAIT 60
2033
Paul Lawrence87999172014-02-20 12:21:31 -08002034static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2035{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002036 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002037 if (fd == -1) {
2038 SLOGE("Error opening file %s", filename);
2039 return -1;
2040 }
2041
2042 char block[CRYPT_INPLACE_BUFSIZE];
2043 memset(block, 0, sizeof(block));
2044 if (unix_read(fd, block, sizeof(block)) < 0) {
2045 SLOGE("Error reading file %s", filename);
2046 close(fd);
2047 return -1;
2048 }
2049
2050 close(fd);
2051
2052 SHA256_CTX c;
2053 SHA256_Init(&c);
2054 SHA256_Update(&c, block, sizeof(block));
2055 SHA256_Final(buf, &c);
2056
2057 return 0;
2058}
2059
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002060static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
2061 char* real_blkdev, int previously_encrypted_upto) {
Paul Lawrence87999172014-02-20 12:21:31 -08002062 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002063 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002064
Paul Lawrence87999172014-02-20 12:21:31 -08002065 /* The size of the userdata partition, and add in the vold volumes below */
2066 tot_encryption_size = crypt_ftr->fs_size;
2067
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002068 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002069 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002070
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002071 if (rc == ENABLE_INPLACE_ERR_DEV) {
2072 /* Hack for b/17898962 */
2073 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2074 cryptfs_reboot(RebootType::reboot);
2075 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002076
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002077 if (!rc) {
2078 crypt_ftr->encrypted_upto = cur_encryption_done;
2079 }
Paul Lawrence87999172014-02-20 12:21:31 -08002080
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002081 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2082 /* The inplace routine never actually sets the progress to 100% due
2083 * to the round down nature of integer division, so set it here */
2084 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002085 }
2086
2087 return rc;
2088}
2089
Paul Crowleyb64933a2017-10-31 08:25:55 -07002090static int vold_unmountAll(void) {
2091 VolumeManager* vm = VolumeManager::Instance();
2092 return vm->unmountAll();
2093}
2094
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002095int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Lawrence87999172014-02-20 12:21:31 -08002096 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Greg Kaiser4a35ef02018-02-09 17:01:06 -08002097 unsigned char decrypted_master_key[DECRYPTED_MASTER_KEY_BUF_SIZE];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002098 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002099 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002100 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002101 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002102 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002103 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002104 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002105 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002106 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002107 bool onlyCreateHeader = false;
2108 int fd = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002109
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002110 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002111 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2112 /* An encryption was underway and was interrupted */
2113 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2114 crypt_ftr.encrypted_upto = 0;
2115 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002116
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002117 /* At this point, we are in an inconsistent state. Until we successfully
2118 complete encryption, a reboot will leave us broken. So mark the
2119 encryption failed in case that happens.
2120 On successfully completing encryption, remove this flag */
2121 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002122
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002123 put_crypt_ftr_and_key(&crypt_ftr);
2124 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2125 if (!check_ftr_sha(&crypt_ftr)) {
2126 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2127 put_crypt_ftr_and_key(&crypt_ftr);
2128 goto error_unencrypted;
2129 }
2130
2131 /* Doing a reboot-encryption*/
2132 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2133 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2134 rebootEncryption = true;
2135 }
Paul Lawrence87999172014-02-20 12:21:31 -08002136 }
2137
2138 property_get("ro.crypto.state", encrypted_state, "");
2139 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2140 SLOGE("Device is already running encrypted, aborting");
2141 goto error_unencrypted;
2142 }
2143
2144 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002145 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2146 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002147
Ken Sumrall3ed82362011-01-28 23:31:16 -08002148 /* Get the size of the real block device */
Wei Wang4375f1b2017-02-24 17:43:01 -08002149 fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002150 if (fd == -1) {
2151 SLOGE("Cannot open block device %s\n", real_blkdev);
2152 goto error_unencrypted;
2153 }
2154 unsigned long nr_sec;
2155 get_blkdev_size(fd, &nr_sec);
2156 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002157 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2158 goto error_unencrypted;
2159 }
2160 close(fd);
2161
2162 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002163 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002164 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002165 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002166 if (fs_size_sec == 0)
2167 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2168
Paul Lawrence87999172014-02-20 12:21:31 -08002169 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002170
2171 if (fs_size_sec > max_fs_size_sec) {
2172 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2173 goto error_unencrypted;
2174 }
2175 }
2176
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002177 /* Get a wakelock as this may take a while, and we don't want the
2178 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2179 * wants to keep the screen on, it can grab a full wakelock.
2180 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002181 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002182 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2183
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002184 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002185 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002186 */
2187 property_set("vold.decrypt", "trigger_shutdown_framework");
2188 SLOGD("Just asked init to shut down class main\n");
2189
Jeff Sharkey9c484982015-03-31 10:35:33 -07002190 /* Ask vold to unmount all devices that it manages */
2191 if (vold_unmountAll()) {
2192 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002193 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002194
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002195 /* no_ui means we are being called from init, not settings.
2196 Now we always reboot from settings, so !no_ui means reboot
2197 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002198 if (!no_ui) {
2199 /* Try fallback, which is to reboot and try there */
2200 onlyCreateHeader = true;
2201 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2202 if (breadcrumb == 0) {
2203 SLOGE("Failed to create breadcrumb file");
2204 goto error_shutting_down;
2205 }
2206 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002207 }
2208
2209 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002210 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002211 /* Now that /data is unmounted, we need to mount a tmpfs
2212 * /data, set a property saying we're doing inplace encryption,
2213 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002214 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002215 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002216 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002217 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002218 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002219 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002220
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002221 /* restart the framework. */
2222 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002223 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002224
Ken Sumrall92736ef2012-10-17 20:57:14 -07002225 /* Ugh, shutting down the framework is not synchronous, so until it
2226 * can be fixed, this horrible hack will wait a moment for it all to
2227 * shut down before proceeding. Without it, some devices cannot
2228 * restart the graphics services.
2229 */
2230 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002231 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002232
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002233 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002234 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002235 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002236 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2237 goto error_shutting_down;
2238 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002239
Paul Lawrence87999172014-02-20 12:21:31 -08002240 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2241 crypt_ftr.fs_size = nr_sec
2242 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2243 } else {
2244 crypt_ftr.fs_size = nr_sec;
2245 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002246 /* At this point, we are in an inconsistent state. Until we successfully
2247 complete encryption, a reboot will leave us broken. So mark the
2248 encryption failed in case that happens.
2249 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002250 if (onlyCreateHeader) {
2251 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2252 } else {
2253 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2254 }
Paul Lawrence87999172014-02-20 12:21:31 -08002255 crypt_ftr.crypt_type = crypt_type;
Greg Kaiser291fec12018-02-09 18:24:59 -08002256 strlcpy((char *)crypt_ftr.crypto_type_name, get_crypt_name(), MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002257
Paul Lawrence87999172014-02-20 12:21:31 -08002258 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002259 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2260 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002261 SLOGE("Cannot create encrypted master key\n");
2262 goto error_shutting_down;
2263 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002264
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002265 /* Replace scrypted intermediate key if we are preparing for a reboot */
2266 if (onlyCreateHeader) {
Greg Kaiser291fec12018-02-09 18:24:59 -08002267 unsigned char fake_master_key[MAX_KEY_LEN];
2268 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002269 memset(fake_master_key, 0, sizeof(fake_master_key));
2270 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
2271 encrypted_fake_master_key, &crypt_ftr);
2272 }
2273
Paul Lawrence87999172014-02-20 12:21:31 -08002274 /* Write the key to the end of the partition */
2275 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002276
Paul Lawrence87999172014-02-20 12:21:31 -08002277 /* If any persistent data has been remembered, save it.
2278 * If none, create a valid empty table and save that.
2279 */
2280 if (!persist_data) {
Wei Wang4375f1b2017-02-24 17:43:01 -08002281 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002282 if (pdata) {
2283 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2284 persist_data = pdata;
2285 }
2286 }
2287 if (persist_data) {
2288 save_persistent_data();
2289 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002290 }
2291
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002292 if (onlyCreateHeader) {
2293 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002294 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002295 }
2296
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002297 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002298 /* startup service classes main and late_start */
2299 property_set("vold.decrypt", "trigger_restart_min_framework");
2300 SLOGD("Just triggered restart_min_framework\n");
2301
2302 /* OK, the framework is restarted and will soon be showing a
2303 * progress bar. Time to setup an encrypted mapping, and
2304 * either write a new filesystem, or encrypt in place updating
2305 * the progress bar as we work.
2306 */
2307 }
2308
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002309 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002310 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002311 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002312
Paul Lawrence87999172014-02-20 12:21:31 -08002313 /* If we are continuing, check checksums match */
2314 rc = 0;
2315 if (previously_encrypted_upto) {
2316 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2317 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002318
Paul Lawrence87999172014-02-20 12:21:31 -08002319 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2320 sizeof(hash_first_block)) != 0) {
2321 SLOGE("Checksums do not match - trigger wipe");
2322 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002323 }
2324 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002325
Paul Lawrence87999172014-02-20 12:21:31 -08002326 if (!rc) {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002327 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002328 previously_encrypted_upto);
2329 }
2330
2331 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002332 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002333 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2334 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002335 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002336 SLOGE("Error calculating checksum for continuing encryption");
2337 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002338 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002339 }
2340
2341 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002342 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002343
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002344 if (! rc) {
2345 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002346 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002347
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002348 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002349 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2350 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002351 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002352 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002353
Paul Lawrence6bfed202014-07-28 12:47:22 -07002354 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002355
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002356 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2357 char value[PROPERTY_VALUE_MAX];
2358 property_get("ro.crypto.state", value, "");
2359 if (!strcmp(value, "")) {
2360 /* default encryption - continue first boot sequence */
2361 property_set("ro.crypto.state", "encrypted");
2362 property_set("ro.crypto.type", "block");
2363 release_wake_lock(lockid);
2364 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2365 // Bring up cryptkeeper that will check the password and set it
2366 property_set("vold.decrypt", "trigger_shutdown_framework");
2367 sleep(2);
2368 property_set("vold.encrypt_progress", "");
2369 cryptfs_trigger_restart_min_framework();
2370 } else {
2371 cryptfs_check_passwd(DEFAULT_PASSWORD);
2372 cryptfs_restart_internal(1);
2373 }
2374 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002375 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002376 sleep(2); /* Give the UI a chance to show 100% progress */
2377 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002378 }
Paul Lawrence87999172014-02-20 12:21:31 -08002379 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002380 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002381 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002382 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002383 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002384 char value[PROPERTY_VALUE_MAX];
2385
Ken Sumrall319369a2012-06-27 16:30:18 -07002386 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002387 if (!strcmp(value, "1")) {
2388 /* wipe data if encryption failed */
2389 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002390 std::string err;
2391 const std::vector<std::string> options = {
2392 "--wipe_data\n--reason=cryptfs_enable_internal\n"
2393 };
2394 if (!write_bootloader_message(options, &err)) {
2395 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002396 }
Josh Gaofec44372017-08-28 13:22:55 -07002397 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002398 } else {
2399 /* set property to trigger dialog */
2400 property_set("vold.encrypt_progress", "error_partially_encrypted");
2401 release_wake_lock(lockid);
2402 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002403 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002404 }
2405
Ken Sumrall3ed82362011-01-28 23:31:16 -08002406 /* hrm, the encrypt step claims success, but the reboot failed.
2407 * This should not happen.
2408 * Set the property and return. Hope the framework can deal with it.
2409 */
2410 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002411 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002412 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002413
2414error_unencrypted:
2415 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002416 if (lockid[0]) {
2417 release_wake_lock(lockid);
2418 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002419 return -1;
2420
2421error_shutting_down:
2422 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2423 * but the framework is stopped and not restarted to show the error, so it's up to
2424 * vold to restart the system.
2425 */
2426 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Josh Gaofec44372017-08-28 13:22:55 -07002427 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002428
2429 /* shouldn't get here */
2430 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002431 if (lockid[0]) {
2432 release_wake_lock(lockid);
2433 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002434 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002435}
2436
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002437int cryptfs_enable(int type, const char* passwd, int no_ui) {
2438 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002439}
2440
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002441int cryptfs_enable_default(int no_ui) {
2442 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002443}
2444
2445int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002446{
Paul Crowley38132a12016-02-09 09:50:32 +00002447 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002448 SLOGE("cryptfs_changepw not valid for file encryption");
2449 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002450 }
2451
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002452 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002453 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002454
2455 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002456 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002457 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002458 return -1;
2459 }
2460
Paul Lawrencef4faa572014-01-29 13:31:03 -08002461 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2462 SLOGE("Invalid crypt_type %d", crypt_type);
2463 return -1;
2464 }
2465
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002466 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002467 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002468 SLOGE("Error getting crypt footer and key");
2469 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002470 }
2471
Paul Lawrencef4faa572014-01-29 13:31:03 -08002472 crypt_ftr.crypt_type = crypt_type;
2473
JP Abgrall933216c2015-02-11 13:44:32 -08002474 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08002475 : newpw,
2476 crypt_ftr.salt,
2477 saved_master_key,
2478 crypt_ftr.master_key,
2479 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002480 if (rc) {
2481 SLOGE("Encrypt master key failed: %d", rc);
2482 return -1;
2483 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002484 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002485 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002486
2487 return 0;
2488}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002489
Rubin Xu85c01f92014-10-13 12:49:54 +01002490static unsigned int persist_get_max_entries(int encrypted) {
2491 struct crypt_mnt_ftr crypt_ftr;
2492 unsigned int dsize;
2493 unsigned int max_persistent_entries;
2494
2495 /* If encrypted, use the values from the crypt_ftr, otherwise
2496 * use the values for the current spec.
2497 */
2498 if (encrypted) {
2499 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2500 return -1;
2501 }
2502 dsize = crypt_ftr.persist_data_size;
2503 } else {
2504 dsize = CRYPT_PERSIST_DATA_SIZE;
2505 }
2506
2507 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2508 sizeof(struct crypt_persist_entry);
2509
2510 return max_persistent_entries;
2511}
2512
2513static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002514{
2515 unsigned int i;
2516
2517 if (persist_data == NULL) {
2518 return -1;
2519 }
2520 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2521 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2522 /* We found it! */
2523 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2524 return 0;
2525 }
2526 }
2527
2528 return -1;
2529}
2530
Rubin Xu85c01f92014-10-13 12:49:54 +01002531static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002532{
2533 unsigned int i;
2534 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002535 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002536
2537 if (persist_data == NULL) {
2538 return -1;
2539 }
2540
Rubin Xu85c01f92014-10-13 12:49:54 +01002541 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002542
2543 num = persist_data->persist_valid_entries;
2544
2545 for (i = 0; i < num; i++) {
2546 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2547 /* We found an existing entry, update it! */
2548 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2549 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2550 return 0;
2551 }
2552 }
2553
2554 /* We didn't find it, add it to the end, if there is room */
2555 if (persist_data->persist_valid_entries < max_persistent_entries) {
2556 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2557 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2558 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2559 persist_data->persist_valid_entries++;
2560 return 0;
2561 }
2562
2563 return -1;
2564}
2565
Rubin Xu85c01f92014-10-13 12:49:54 +01002566/**
2567 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2568 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2569 */
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002570int match_multi_entry(const char *key, const char *field, unsigned index) {
2571 std::string key_ = key;
2572 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002573
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002574 std::string parsed_field;
2575 unsigned parsed_index;
2576
2577 std::string::size_type split = key_.find_last_of('_');
2578 if (split == std::string::npos) {
2579 parsed_field = key_;
2580 parsed_index = 0;
2581 } else {
2582 parsed_field = key_.substr(0, split);
2583 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002584 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002585
2586 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002587}
2588
2589/*
2590 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2591 * remaining entries starting from index will be deleted.
2592 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2593 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2594 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2595 *
2596 */
2597static int persist_del_keys(const char *fieldname, unsigned index)
2598{
2599 unsigned int i;
2600 unsigned int j;
2601 unsigned int num;
2602
2603 if (persist_data == NULL) {
2604 return PERSIST_DEL_KEY_ERROR_OTHER;
2605 }
2606
2607 num = persist_data->persist_valid_entries;
2608
2609 j = 0; // points to the end of non-deleted entries.
2610 // Filter out to-be-deleted entries in place.
2611 for (i = 0; i < num; i++) {
2612 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2613 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2614 j++;
2615 }
2616 }
2617
2618 if (j < num) {
2619 persist_data->persist_valid_entries = j;
2620 // Zeroise the remaining entries
2621 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2622 return PERSIST_DEL_KEY_OK;
2623 } else {
2624 // Did not find an entry matching the given fieldname
2625 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2626 }
2627}
2628
2629static int persist_count_keys(const char *fieldname)
2630{
2631 unsigned int i;
2632 unsigned int count;
2633
2634 if (persist_data == NULL) {
2635 return -1;
2636 }
2637
2638 count = 0;
2639 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2640 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2641 count++;
2642 }
2643 }
2644
2645 return count;
2646}
2647
Ken Sumrall160b4d62013-04-22 12:15:39 -07002648/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002649int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002650{
Paul Crowley38132a12016-02-09 09:50:32 +00002651 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002652 SLOGE("Cannot get field when file encrypted");
2653 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002654 }
2655
Ken Sumrall160b4d62013-04-22 12:15:39 -07002656 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002657 /* CRYPTO_GETFIELD_OK is success,
2658 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2659 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2660 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002661 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002662 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2663 int i;
2664 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002665
2666 if (persist_data == NULL) {
2667 load_persistent_data();
2668 if (persist_data == NULL) {
2669 SLOGE("Getfield error, cannot load persistent data");
2670 goto out;
2671 }
2672 }
2673
Rubin Xu85c01f92014-10-13 12:49:54 +01002674 // Read value from persistent entries. If the original value is split into multiple entries,
2675 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002676 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002677 // We found it, copy it to the caller's buffer and keep going until all entries are read.
2678 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
2679 // value too small
2680 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2681 goto out;
2682 }
2683 rc = CRYPTO_GETFIELD_OK;
2684
2685 for (i = 1; /* break explicitly */; i++) {
2686 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
2687 (int) sizeof(temp_field)) {
2688 // If the fieldname is very long, we stop as soon as it begins to overflow the
2689 // maximum field length. At this point we have in fact fully read out the original
2690 // value because cryptfs_setfield would not allow fields with longer names to be
2691 // written in the first place.
2692 break;
2693 }
2694 if (!persist_get_key(temp_field, temp_value)) {
2695 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2696 // value too small.
2697 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2698 goto out;
2699 }
2700 } else {
2701 // Exhaust all entries.
2702 break;
2703 }
2704 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002705 } else {
2706 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002707 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002708 }
2709
2710out:
2711 return rc;
2712}
2713
2714/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002715int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002716{
Paul Crowley38132a12016-02-09 09:50:32 +00002717 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002718 SLOGE("Cannot set field when file encrypted");
2719 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002720 }
2721
Ken Sumrall160b4d62013-04-22 12:15:39 -07002722 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002723 /* 0 is success, negative values are error */
2724 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002725 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002726 unsigned int field_id;
2727 char temp_field[PROPERTY_KEY_MAX];
2728 unsigned int num_entries;
2729 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002730
2731 if (persist_data == NULL) {
2732 load_persistent_data();
2733 if (persist_data == NULL) {
2734 SLOGE("Setfield error, cannot load persistent data");
2735 goto out;
2736 }
2737 }
2738
2739 property_get("ro.crypto.state", encrypted_state, "");
2740 if (!strcmp(encrypted_state, "encrypted") ) {
2741 encrypted = 1;
2742 }
2743
Rubin Xu85c01f92014-10-13 12:49:54 +01002744 // Compute the number of entries required to store value, each entry can store up to
2745 // (PROPERTY_VALUE_MAX - 1) chars
2746 if (strlen(value) == 0) {
2747 // Empty value also needs one entry to store.
2748 num_entries = 1;
2749 } else {
2750 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2751 }
2752
2753 max_keylen = strlen(fieldname);
2754 if (num_entries > 1) {
2755 // Need an extra "_%d" suffix.
2756 max_keylen += 1 + log10(num_entries);
2757 }
2758 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2759 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002760 goto out;
2761 }
2762
Rubin Xu85c01f92014-10-13 12:49:54 +01002763 // Make sure we have enough space to write the new value
2764 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2765 persist_get_max_entries(encrypted)) {
2766 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2767 goto out;
2768 }
2769
2770 // Now that we know persist_data has enough space for value, let's delete the old field first
2771 // to make up space.
2772 persist_del_keys(fieldname, 0);
2773
2774 if (persist_set_key(fieldname, value, encrypted)) {
2775 // fail to set key, should not happen as we have already checked the available space
2776 SLOGE("persist_set_key() error during setfield()");
2777 goto out;
2778 }
2779
2780 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002781 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002782
2783 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2784 // fail to set key, should not happen as we have already checked the available space.
2785 SLOGE("persist_set_key() error during setfield()");
2786 goto out;
2787 }
2788 }
2789
Ken Sumrall160b4d62013-04-22 12:15:39 -07002790 /* If we are running encrypted, save the persistent data now */
2791 if (encrypted) {
2792 if (save_persistent_data()) {
2793 SLOGE("Setfield error, cannot save persistent data");
2794 goto out;
2795 }
2796 }
2797
Rubin Xu85c01f92014-10-13 12:49:54 +01002798 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002799
2800out:
2801 return rc;
2802}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002803
2804/* Checks userdata. Attempt to mount the volume if default-
2805 * encrypted.
2806 * On success trigger next init phase and return 0.
2807 * Currently do not handle failure - see TODO below.
2808 */
2809int cryptfs_mount_default_encrypted(void)
2810{
Paul Lawrence84274cc2016-04-15 15:41:33 -07002811 int crypt_type = cryptfs_get_password_type();
2812 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2813 SLOGE("Bad crypt type - error");
2814 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2815 SLOGD("Password is not default - "
2816 "starting min framework to prompt");
2817 property_set("vold.decrypt", "trigger_restart_min_framework");
2818 return 0;
2819 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2820 SLOGD("Password is default - restarting filesystem");
2821 cryptfs_restart_internal(0);
2822 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002823 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002824 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002825 }
2826
Paul Lawrence6bfed202014-07-28 12:47:22 -07002827 /** Corrupt. Allow us to boot into framework, which will detect bad
2828 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002829 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002830 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002831 return 0;
2832}
2833
2834/* Returns type of the password, default, pattern, pin or password.
2835 */
2836int cryptfs_get_password_type(void)
2837{
Paul Crowley38132a12016-02-09 09:50:32 +00002838 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002839 SLOGE("cryptfs_get_password_type not valid for file encryption");
2840 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002841 }
2842
Paul Lawrencef4faa572014-01-29 13:31:03 -08002843 struct crypt_mnt_ftr crypt_ftr;
2844
2845 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2846 SLOGE("Error getting crypt footer and key\n");
2847 return -1;
2848 }
2849
Paul Lawrence6bfed202014-07-28 12:47:22 -07002850 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2851 return -1;
2852 }
2853
Paul Lawrencef4faa572014-01-29 13:31:03 -08002854 return crypt_ftr.crypt_type;
2855}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002856
Paul Lawrence05335c32015-03-05 09:46:23 -08002857const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002858{
Paul Crowley38132a12016-02-09 09:50:32 +00002859 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002860 SLOGE("cryptfs_get_password not valid for file encryption");
2861 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002862 }
2863
Paul Lawrence399317e2014-03-10 13:20:50 -07002864 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002865 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002866 if (now.tv_sec < password_expiry_time) {
2867 return password;
2868 } else {
2869 cryptfs_clear_password();
2870 return 0;
2871 }
2872}
2873
2874void cryptfs_clear_password()
2875{
2876 if (password) {
2877 size_t len = strlen(password);
2878 memset(password, 0, len);
2879 free(password);
2880 password = 0;
2881 password_expiry_time = 0;
2882 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002883}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002884
Paul Lawrence0c247462015-10-29 10:30:57 -07002885int cryptfs_isConvertibleToFBE()
2886{
Paul Crowleye2ee1522017-09-26 14:05:26 -07002887 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Paul Lawrence0c247462015-10-29 10:30:57 -07002888 return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
2889}