blob: 8c66e0153f3b62a17d826f4cdd02572ed836f506 [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
23#include <sys/types.h>
Ken Sumralle550f782013-08-20 13:48:23 -070024#include <sys/wait.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080025#include <sys/stat.h>
Paul Lawrencef4faa572014-01-29 13:31:03 -080026#include <ctype.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080027#include <fcntl.h>
Elliott Hughes73737162014-06-25 17:27:42 -070028#include <inttypes.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080029#include <unistd.h>
30#include <stdio.h>
31#include <sys/ioctl.h>
32#include <linux/dm-ioctl.h>
33#include <libgen.h>
34#include <stdlib.h>
35#include <sys/param.h>
36#include <string.h>
37#include <sys/mount.h>
38#include <openssl/evp.h>
Adam Langley41405bb2015-01-22 16:45:28 -080039#include <openssl/sha.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080040#include <errno.h>
Paul Crowley3b71fc52017-10-09 10:55:21 -070041#include <ext4_utils/ext4_crypt.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070042#include <ext4_utils/ext4_utils.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070043#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070044#include <fs_mgr.h>
Paul Lawrence9c58a872014-09-30 09:12:51 -070045#include <time.h>
Rubin Xu85c01f92014-10-13 12:49:54 +010046#include <math.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080047#include <selinux/selinux.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080048#include "cryptfs.h"
Jeff Vander Stoepdf725752016-01-29 15:34:43 -080049#include "secontext.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080050#define LOG_TAG "Cryptfs"
51#include "cutils/log.h"
52#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070053#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080054#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070055#include <logwrap/logwrap.h>
Paul Crowley63c18d32016-02-10 14:02:47 +000056#include "ScryptParameters.h"
Ken Sumrall29d8da82011-05-18 17:20:07 -070057#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070058#include "VoldUtil.h"
Paul Lawrence731a7a22015-04-28 22:14:15 +000059#include "Ext4Crypt.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000060#include "f2fs_sparseblock.h"
Paul Crowleyf71ace32016-06-02 11:01:19 -070061#include "EncryptInplace.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080062#include "Process.h"
Janis Danisevskis015ec302017-01-31 11:31:08 +000063#include "Keymaster.h"
Wei Wang4375f1b2017-02-24 17:43:01 -080064#include "android-base/properties.h"
Yabin Cui1fb59662016-06-24 14:48:49 -070065#include <bootloader_message/bootloader_message.h>
Wei Wang4375f1b2017-02-24 17:43:01 -080066extern "C" {
67#include <crypto_scrypt.h>
68}
Mark Salyzyn3e971272014-01-21 13:27:04 -080069
Mark Salyzyn5eecc442014-02-12 14:16:14 -080070#define UNUSED __attribute__((unused))
71
Ken Sumrall8f869aa2010-12-03 03:47:09 -080072#define DM_CRYPT_BUF_SIZE 4096
73
Jason parks70a4b3f2011-01-28 10:10:47 -060074#define HASH_COUNT 2000
Greg Kaiser59ad0182018-02-16 13:01:36 -080075#define DEFAULT_KEY_LEN_BYTES 16
Greg Kaiserc0de9c72018-02-14 20:05:54 -080076
77constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
78constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
79constexpr size_t INTERMEDIATE_BUF_SIZE =
80 (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
81
82// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
83static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN,
84 "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -060085
Ken Sumrall29d8da82011-05-18 17:20:07 -070086#define KEY_IN_FOOTER "footer"
87
Paul Lawrence3bd36d52015-06-09 13:37:44 -070088#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080089
Paul Lawrence3d99eba2015-11-20 07:07:19 -080090#define CRYPTO_BLOCK_DEVICE "userdata"
91
92#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
93
Ken Sumrall29d8da82011-05-18 17:20:07 -070094#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070095#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070096
Ken Sumralle919efe2012-09-29 17:07:41 -070097#define TABLE_LOAD_RETRIES 10
98
Shawn Willden47ba10d2014-09-03 17:07:06 -060099#define RSA_KEY_SIZE 2048
100#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
101#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600102#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700103
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700104#define RETRY_MOUNT_ATTEMPTS 10
105#define RETRY_MOUNT_DELAY_SECONDS 1
106
Paul Crowley5afbc622017-11-27 09:42:17 -0800107#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
108
Paul Crowley73473332017-11-21 15:43:51 -0800109static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
110
Greg Kaiser59ad0182018-02-16 13:01:36 -0800111static unsigned char saved_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -0700112static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -0600113static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700114static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800115
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700116/* Should we use keymaster? */
117static int keymaster_check_compatibility()
118{
Janis Danisevskis015ec302017-01-31 11:31:08 +0000119 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700120}
121
122/* Create a new keymaster key and store it in this footer */
123static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
124{
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800125 if (ftr->keymaster_blob_size) {
126 SLOGI("Already have key");
127 return 0;
128 }
129
Janis Danisevskis015ec302017-01-31 11:31:08 +0000130 int rc = keymaster_create_key_for_cryptfs_scrypt(RSA_KEY_SIZE, RSA_EXPONENT,
131 KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
132 &ftr->keymaster_blob_size);
133 if (rc) {
134 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800135 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000136 ftr->keymaster_blob_size = 0;
137 }
138 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700139 return -1;
140 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000141 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700142}
143
Shawn Willdene17a9c42014-09-08 13:04:08 -0600144/* This signs the given object using the keymaster key. */
145static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600146 const unsigned char *object,
147 const size_t object_size,
148 unsigned char **signature,
149 size_t *signature_size)
150{
Shawn Willden47ba10d2014-09-03 17:07:06 -0600151 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600152 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600153 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600154
Shawn Willdene17a9c42014-09-08 13:04:08 -0600155 // To sign a message with RSA, the message must satisfy two
156 // constraints:
157 //
158 // 1. The message, when interpreted as a big-endian numeric value, must
159 // be strictly less than the public modulus of the RSA key. Note
160 // that because the most significant bit of the public modulus is
161 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
162 // key), an n-bit message with most significant bit 0 always
163 // satisfies this requirement.
164 //
165 // 2. The message must have the same length in bits as the public
166 // modulus of the RSA key. This requirement isn't mathematically
167 // necessary, but is necessary to ensure consistency in
168 // implementations.
169 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600170 case KDF_SCRYPT_KEYMASTER:
171 // This ensures the most significant byte of the signed message
172 // is zero. We could have zero-padded to the left instead, but
173 // this approach is slightly more robust against changes in
174 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600175 // so) because we really should be using a proper deterministic
176 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800177 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600178 SLOGI("Signing safely-padded object");
179 break;
180 default:
181 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000182 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600183 }
Paul Crowley73473332017-11-21 15:43:51 -0800184 for (;;) {
185 auto result = keymaster_sign_object_for_cryptfs_scrypt(
186 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
187 to_sign_size, signature, signature_size);
188 switch (result) {
189 case KeymasterSignResult::ok:
190 return 0;
191 case KeymasterSignResult::upgrade:
192 break;
193 default:
194 return -1;
195 }
196 SLOGD("Upgrading key");
197 if (keymaster_upgrade_key_for_cryptfs_scrypt(
198 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
199 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
200 &ftr->keymaster_blob_size) != 0) {
201 SLOGE("Failed to upgrade key");
202 return -1;
203 }
204 if (put_crypt_ftr_and_key(ftr) != 0) {
205 SLOGE("Failed to write upgraded key to disk");
206 }
207 SLOGD("Key upgraded successfully");
208 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600209}
210
Paul Lawrence399317e2014-03-10 13:20:50 -0700211/* Store password when userdata is successfully decrypted and mounted.
212 * Cleared by cryptfs_clear_password
213 *
214 * To avoid a double prompt at boot, we need to store the CryptKeeper
215 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
216 * Since the entire framework is torn down and rebuilt after encryption,
217 * we have to use a daemon or similar to store the password. Since vold
218 * is secured against IPC except from system processes, it seems a reasonable
219 * place to store this.
220 *
221 * password should be cleared once it has been used.
222 *
223 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800224 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700225static char* password = 0;
226static int password_expiry_time = 0;
227static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800228
Josh Gaofec44372017-08-28 13:22:55 -0700229enum class RebootType {reboot, recovery, shutdown};
230static void cryptfs_reboot(RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700231{
Josh Gaofec44372017-08-28 13:22:55 -0700232 switch (rt) {
233 case RebootType::reboot:
Paul Lawrence87999172014-02-20 12:21:31 -0800234 property_set(ANDROID_RB_PROPERTY, "reboot");
235 break;
236
Josh Gaofec44372017-08-28 13:22:55 -0700237 case RebootType::recovery:
Paul Lawrence87999172014-02-20 12:21:31 -0800238 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
239 break;
240
Josh Gaofec44372017-08-28 13:22:55 -0700241 case RebootType::shutdown:
Paul Lawrence87999172014-02-20 12:21:31 -0800242 property_set(ANDROID_RB_PROPERTY, "shutdown");
243 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700244 }
Paul Lawrence87999172014-02-20 12:21:31 -0800245
Ken Sumralladfba362013-06-04 16:37:52 -0700246 sleep(20);
247
248 /* Shouldn't get here, reboot should happen before sleep times out */
249 return;
250}
251
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800252static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
253{
254 memset(io, 0, dataSize);
255 io->data_size = dataSize;
256 io->data_start = sizeof(struct dm_ioctl);
257 io->version[0] = 4;
258 io->version[1] = 0;
259 io->version[2] = 0;
260 io->flags = flags;
261 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100262 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800263 }
264}
265
Kenny Rootc4c70f12013-06-14 12:11:38 -0700266/**
267 * Gets the default device scrypt parameters for key derivation time tuning.
268 * The parameters should lead to about one second derivation time for the
269 * given device.
270 */
271static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700272 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000273 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700274
Paul Crowley63c18d32016-02-10 14:02:47 +0000275 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
276 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
277 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
278 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700279 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000280 ftr->N_factor = Nf;
281 ftr->r_factor = rf;
282 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700283}
284
Ken Sumrall3ed82362011-01-28 23:31:16 -0800285static unsigned int get_fs_size(char *dev)
286{
287 int fd, block_size;
288 struct ext4_super_block sb;
289 off64_t len;
290
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700291 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800292 SLOGE("Cannot open device to get filesystem size ");
293 return 0;
294 }
295
296 if (lseek64(fd, 1024, SEEK_SET) < 0) {
297 SLOGE("Cannot seek to superblock");
298 return 0;
299 }
300
301 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
302 SLOGE("Cannot read superblock");
303 return 0;
304 }
305
306 close(fd);
307
Daniel Rosenberge82df162014-08-15 22:19:23 +0000308 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
309 SLOGE("Not a valid ext4 superblock");
310 return 0;
311 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800312 block_size = 1024 << sb.s_log_block_size;
313 /* compute length in bytes */
314 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
315
316 /* return length in sectors */
317 return (unsigned int) (len / 512);
318}
319
Ken Sumrall160b4d62013-04-22 12:15:39 -0700320static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
321{
322 static int cached_data = 0;
323 static off64_t cached_off = 0;
324 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
325 int fd;
326 char key_loc[PROPERTY_VALUE_MAX];
327 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700328 int rc = -1;
329
330 if (!cached_data) {
Paul Crowleye2ee1522017-09-26 14:05:26 -0700331 fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700332
333 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700334 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700335 SLOGE("Cannot open real block device %s\n", real_blkdev);
336 return -1;
337 }
338
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900339 unsigned long nr_sec = 0;
340 get_blkdev_size(fd, &nr_sec);
341 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700342 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
343 * encryption info footer and key, and plenty of bytes to spare for future
344 * growth.
345 */
346 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
347 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
348 cached_data = 1;
349 } else {
350 SLOGE("Cannot get size of block device %s\n", real_blkdev);
351 }
352 close(fd);
353 } else {
354 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
355 cached_off = 0;
356 cached_data = 1;
357 }
358 }
359
360 if (cached_data) {
361 if (metadata_fname) {
362 *metadata_fname = cached_metadata_fname;
363 }
364 if (off) {
365 *off = cached_off;
366 }
367 rc = 0;
368 }
369
370 return rc;
371}
372
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800373/* Set sha256 checksum in structure */
374static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr)
375{
376 SHA256_CTX c;
377 SHA256_Init(&c);
378 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
379 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
380 SHA256_Final(crypt_ftr->sha256, &c);
381}
382
Ken Sumralle8744072011-01-18 22:01:55 -0800383/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800384 * update the failed mount count but not change the key.
385 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700386static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800387{
388 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800389 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700390 /* starting_off is set to the SEEK_SET offset
391 * where the crypto structure starts
392 */
393 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800394 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700395 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700396 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800397
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800398 set_ftr_sha(crypt_ftr);
399
Ken Sumrall160b4d62013-04-22 12:15:39 -0700400 if (get_crypt_ftr_info(&fname, &starting_off)) {
401 SLOGE("Unable to get crypt_ftr_info\n");
402 return -1;
403 }
404 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700405 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700406 return -1;
407 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700408 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700409 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700410 return -1;
411 }
412
413 /* Seek to the start of the crypt footer */
414 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
415 SLOGE("Cannot seek to real block device footer\n");
416 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800417 }
418
419 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
420 SLOGE("Cannot write real block device footer\n");
421 goto errout;
422 }
423
Ken Sumrall3be890f2011-09-14 16:53:46 -0700424 fstat(fd, &statbuf);
425 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700426 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700427 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800428 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800429 goto errout;
430 }
431 }
432
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800433 /* Success! */
434 rc = 0;
435
436errout:
437 close(fd);
438 return rc;
439
440}
441
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800442static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr)
443{
444 struct crypt_mnt_ftr copy;
445 memcpy(&copy, crypt_ftr, sizeof(copy));
446 set_ftr_sha(&copy);
447 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
448}
449
Ken Sumrall160b4d62013-04-22 12:15:39 -0700450static inline int unix_read(int fd, void* buff, int len)
451{
452 return TEMP_FAILURE_RETRY(read(fd, buff, len));
453}
454
455static inline int unix_write(int fd, const void* buff, int len)
456{
457 return TEMP_FAILURE_RETRY(write(fd, buff, len));
458}
459
460static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
461{
462 memset(pdata, 0, len);
463 pdata->persist_magic = PERSIST_DATA_MAGIC;
464 pdata->persist_valid_entries = 0;
465}
466
467/* A routine to update the passed in crypt_ftr to the lastest version.
468 * fd is open read/write on the device that holds the crypto footer and persistent
469 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
470 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
471 */
472static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
473{
Kenny Root7434b312013-06-14 11:29:53 -0700474 int orig_major = crypt_ftr->major_version;
475 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700476
Kenny Root7434b312013-06-14 11:29:53 -0700477 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
478 struct crypt_persist_data *pdata;
479 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700480
Kenny Rootc4c70f12013-06-14 12:11:38 -0700481 SLOGW("upgrading crypto footer to 1.1");
482
Wei Wang4375f1b2017-02-24 17:43:01 -0800483 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700484 if (pdata == NULL) {
485 SLOGE("Cannot allocate persisent data\n");
486 return;
487 }
488 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
489
490 /* Need to initialize the persistent data area */
491 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
492 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100493 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700494 return;
495 }
496 /* Write all zeros to the first copy, making it invalid */
497 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
498
499 /* Write a valid but empty structure to the second copy */
500 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
501 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
502
503 /* Update the footer */
504 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
505 crypt_ftr->persist_data_offset[0] = pdata_offset;
506 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
507 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100508 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700509 }
510
Paul Lawrencef4faa572014-01-29 13:31:03 -0800511 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700512 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800513 /* But keep the old kdf_type.
514 * It will get updated later to KDF_SCRYPT after the password has been verified.
515 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700516 crypt_ftr->kdf_type = KDF_PBKDF2;
517 get_device_scrypt_params(crypt_ftr);
518 crypt_ftr->minor_version = 2;
519 }
520
Paul Lawrencef4faa572014-01-29 13:31:03 -0800521 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
522 SLOGW("upgrading crypto footer to 1.3");
523 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
524 crypt_ftr->minor_version = 3;
525 }
526
Kenny Root7434b312013-06-14 11:29:53 -0700527 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
528 if (lseek64(fd, offset, SEEK_SET) == -1) {
529 SLOGE("Cannot seek to crypt footer\n");
530 return;
531 }
532 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700533 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700534}
535
536
537static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800538{
539 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800540 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700541 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800542 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700543 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700544 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800545
Ken Sumrall160b4d62013-04-22 12:15:39 -0700546 if (get_crypt_ftr_info(&fname, &starting_off)) {
547 SLOGE("Unable to get crypt_ftr_info\n");
548 return -1;
549 }
550 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700551 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700552 return -1;
553 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700554 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700555 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700556 return -1;
557 }
558
559 /* Make sure it's 16 Kbytes in length */
560 fstat(fd, &statbuf);
561 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
562 SLOGE("footer file %s is not the expected size!\n", fname);
563 goto errout;
564 }
565
566 /* Seek to the start of the crypt footer */
567 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
568 SLOGE("Cannot seek to real block device footer\n");
569 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800570 }
571
572 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
573 SLOGE("Cannot read real block device footer\n");
574 goto errout;
575 }
576
577 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700578 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800579 goto errout;
580 }
581
Kenny Rootc96a5f82013-06-14 12:08:28 -0700582 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
583 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
584 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800585 goto errout;
586 }
587
Greg Kaiser59ad0182018-02-16 13:01:36 -0800588 // We risk buffer overflows with oversized keys, so we just reject them.
589 // 0-sized keys are problematic (essentially by-passing encryption), and
590 // AES-CBC key wrapping only works for multiples of 16 bytes.
591 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
592 (crypt_ftr->keysize > MAX_KEY_LEN)) {
593 SLOGE("Invalid keysize (%u) for block device %s; Must be non-zero, "
594 "divisible by 16, and <= %d\n", crypt_ftr->keysize, fname,
595 MAX_KEY_LEN);
596 goto errout;
597 }
598
Kenny Rootc96a5f82013-06-14 12:08:28 -0700599 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
600 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
601 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800602 }
603
Ken Sumrall160b4d62013-04-22 12:15:39 -0700604 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
605 * copy on disk before returning.
606 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700607 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700608 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800609 }
610
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800611 /* Success! */
612 rc = 0;
613
614errout:
615 close(fd);
616 return rc;
617}
618
Ken Sumrall160b4d62013-04-22 12:15:39 -0700619static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
620{
621 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
622 crypt_ftr->persist_data_offset[1]) {
623 SLOGE("Crypt_ftr persist data regions overlap");
624 return -1;
625 }
626
627 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
628 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
629 return -1;
630 }
631
632 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
633 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
634 CRYPT_FOOTER_OFFSET) {
635 SLOGE("Persistent data extends past crypto footer");
636 return -1;
637 }
638
639 return 0;
640}
641
642static int load_persistent_data(void)
643{
644 struct crypt_mnt_ftr crypt_ftr;
645 struct crypt_persist_data *pdata = NULL;
646 char encrypted_state[PROPERTY_VALUE_MAX];
647 char *fname;
648 int found = 0;
649 int fd;
650 int ret;
651 int i;
652
653 if (persist_data) {
654 /* Nothing to do, we've already loaded or initialized it */
655 return 0;
656 }
657
658
659 /* If not encrypted, just allocate an empty table and initialize it */
660 property_get("ro.crypto.state", encrypted_state, "");
661 if (strcmp(encrypted_state, "encrypted") ) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800662 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700663 if (pdata) {
664 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
665 persist_data = pdata;
666 return 0;
667 }
668 return -1;
669 }
670
671 if(get_crypt_ftr_and_key(&crypt_ftr)) {
672 return -1;
673 }
674
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700675 if ((crypt_ftr.major_version < 1)
676 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700677 SLOGE("Crypt_ftr version doesn't support persistent data");
678 return -1;
679 }
680
681 if (get_crypt_ftr_info(&fname, NULL)) {
682 return -1;
683 }
684
685 ret = validate_persistent_data_storage(&crypt_ftr);
686 if (ret) {
687 return -1;
688 }
689
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700690 fd = open(fname, O_RDONLY|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700691 if (fd < 0) {
692 SLOGE("Cannot open %s metadata file", fname);
693 return -1;
694 }
695
Wei Wang4375f1b2017-02-24 17:43:01 -0800696 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800697 if (pdata == NULL) {
698 SLOGE("Cannot allocate memory for persistent data");
699 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700700 }
701
702 for (i = 0; i < 2; i++) {
703 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
704 SLOGE("Cannot seek to read persistent data on %s", fname);
705 goto err2;
706 }
707 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
708 SLOGE("Error reading persistent data on iteration %d", i);
709 goto err2;
710 }
711 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
712 found = 1;
713 break;
714 }
715 }
716
717 if (!found) {
718 SLOGI("Could not find valid persistent data, creating");
719 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
720 }
721
722 /* Success */
723 persist_data = pdata;
724 close(fd);
725 return 0;
726
727err2:
728 free(pdata);
729
730err:
731 close(fd);
732 return -1;
733}
734
735static int save_persistent_data(void)
736{
737 struct crypt_mnt_ftr crypt_ftr;
738 struct crypt_persist_data *pdata;
739 char *fname;
740 off64_t write_offset;
741 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700742 int fd;
743 int ret;
744
745 if (persist_data == NULL) {
746 SLOGE("No persistent data to save");
747 return -1;
748 }
749
750 if(get_crypt_ftr_and_key(&crypt_ftr)) {
751 return -1;
752 }
753
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700754 if ((crypt_ftr.major_version < 1)
755 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700756 SLOGE("Crypt_ftr version doesn't support persistent data");
757 return -1;
758 }
759
760 ret = validate_persistent_data_storage(&crypt_ftr);
761 if (ret) {
762 return -1;
763 }
764
765 if (get_crypt_ftr_info(&fname, NULL)) {
766 return -1;
767 }
768
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700769 fd = open(fname, O_RDWR|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700770 if (fd < 0) {
771 SLOGE("Cannot open %s metadata file", fname);
772 return -1;
773 }
774
Wei Wang4375f1b2017-02-24 17:43:01 -0800775 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700776 if (pdata == NULL) {
777 SLOGE("Cannot allocate persistant data");
778 goto err;
779 }
780
781 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
782 SLOGE("Cannot seek to read persistent data on %s", fname);
783 goto err2;
784 }
785
786 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
787 SLOGE("Error reading persistent data before save");
788 goto err2;
789 }
790
791 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
792 /* The first copy is the curent valid copy, so write to
793 * the second copy and erase this one */
794 write_offset = crypt_ftr.persist_data_offset[1];
795 erase_offset = crypt_ftr.persist_data_offset[0];
796 } else {
797 /* The second copy must be the valid copy, so write to
798 * the first copy, and erase the second */
799 write_offset = crypt_ftr.persist_data_offset[0];
800 erase_offset = crypt_ftr.persist_data_offset[1];
801 }
802
803 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100804 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700805 SLOGE("Cannot seek to write persistent data");
806 goto err2;
807 }
808 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
809 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100810 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700811 SLOGE("Cannot seek to erase previous persistent data");
812 goto err2;
813 }
814 fsync(fd);
815 memset(pdata, 0, crypt_ftr.persist_data_size);
816 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
817 (int) crypt_ftr.persist_data_size) {
818 SLOGE("Cannot write to erase previous persistent data");
819 goto err2;
820 }
821 fsync(fd);
822 } else {
823 SLOGE("Cannot write to save persistent data");
824 goto err2;
825 }
826
827 /* Success */
828 free(pdata);
829 close(fd);
830 return 0;
831
832err2:
833 free(pdata);
834err:
835 close(fd);
836 return -1;
837}
838
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800839/* Convert a binary key of specified length into an ascii hex string equivalent,
840 * without the leading 0x and with null termination
841 */
Jeff Sharkey9c484982015-03-31 10:35:33 -0700842static void convert_key_to_hex_ascii(const unsigned char *master_key,
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700843 unsigned int keysize, char *master_key_ascii) {
844 unsigned int i, a;
845 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800846
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700847 for (i=0, a=0; i<keysize; i++, a+=2) {
848 /* For each byte, write out two ascii hex digits */
849 nibble = (master_key[i] >> 4) & 0xf;
850 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800851
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700852 nibble = master_key[i] & 0xf;
853 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
854 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800855
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700856 /* Add the null termination */
857 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800858
859}
860
Jeff Sharkey9c484982015-03-31 10:35:33 -0700861static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
862 const unsigned char *master_key, const char *real_blk_name,
863 const char *name, int fd, const char *extra_params) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800864 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800865 struct dm_ioctl *io;
866 struct dm_target_spec *tgt;
867 char *crypt_params;
Greg Kaiser59ad0182018-02-16 13:01:36 -0800868 // We need two ASCII characters to represent each byte, and need space for
869 // the '\0' terminator.
870 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
George Burgess IV605d7ae2016-02-29 13:39:17 -0800871 size_t buff_offset;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800872 int i;
873
874 io = (struct dm_ioctl *) buffer;
875
876 /* Load the mapping table for this device */
877 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
878
879 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
880 io->target_count = 1;
881 tgt->status = 0;
882 tgt->sector_start = 0;
883 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -0700884 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800885
886 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
887 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800888
889 buff_offset = crypt_params - buffer;
Paul Crowley5afbc622017-11-27 09:42:17 -0800890 SLOGI("Extra parameters for dm_crypt: %s\n", extra_params);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800891 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
892 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name,
893 extra_params);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800894 crypt_params += strlen(crypt_params) + 1;
895 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
896 tgt->next = crypt_params - buffer;
897
898 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
899 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
900 break;
901 }
902 usleep(500000);
903 }
904
905 if (i == TABLE_LOAD_RETRIES) {
906 /* We failed to load the table, return an error */
907 return -1;
908 } else {
909 return i + 1;
910 }
911}
912
913
914static int get_dm_crypt_version(int fd, const char *name, int *version)
915{
916 char buffer[DM_CRYPT_BUF_SIZE];
917 struct dm_ioctl *io;
918 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800919
920 io = (struct dm_ioctl *) buffer;
921
922 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
923
924 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
925 return -1;
926 }
927
928 /* Iterate over the returned versions, looking for name of "crypt".
929 * When found, get and return the version.
930 */
931 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
932 while (v->next) {
933 if (! strcmp(v->name, "crypt")) {
934 /* We found the crypt driver, return the version, and get out */
935 version[0] = v->version[0];
936 version[1] = v->version[1];
937 version[2] = v->version[2];
938 return 0;
939 }
940 v = (struct dm_target_versions *)(((char *)v) + v->next);
941 }
942
943 return -1;
944}
945
Paul Crowley5afbc622017-11-27 09:42:17 -0800946static std::string extra_params_as_string(const std::vector<std::string>& extra_params_vec) {
947 if (extra_params_vec.empty()) return "";
948 std::string extra_params = std::to_string(extra_params_vec.size());
949 for (const auto& p : extra_params_vec) {
950 extra_params.append(" ");
951 extra_params.append(p);
952 }
953 return extra_params;
954}
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800955
Paul Crowley5afbc622017-11-27 09:42:17 -0800956static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
957 const char* real_blk_name, char* crypto_blk_name, const char* name,
958 uint32_t flags) {
959 char buffer[DM_CRYPT_BUF_SIZE];
960 struct dm_ioctl* io;
961 unsigned int minor;
962 int fd = 0;
963 int err;
964 int retval = -1;
965 int version[3];
966 int load_count;
967 std::vector<std::string> extra_params_vec;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800968
Paul Crowley5afbc622017-11-27 09:42:17 -0800969 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
970 SLOGE("Cannot open device-mapper\n");
971 goto errout;
972 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800973
Paul Crowley5afbc622017-11-27 09:42:17 -0800974 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800975
Paul Crowley5afbc622017-11-27 09:42:17 -0800976 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
977 err = ioctl(fd, DM_DEV_CREATE, io);
978 if (err) {
979 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
980 goto errout;
981 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800982
Paul Crowley5afbc622017-11-27 09:42:17 -0800983 /* Get the device status, in particular, the name of it's device file */
984 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
985 if (ioctl(fd, DM_DEV_STATUS, io)) {
986 SLOGE("Cannot retrieve dm-crypt device status\n");
987 goto errout;
988 }
989 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
990 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
Ken Sumralle919efe2012-09-29 17:07:41 -0700991
Paul Crowley5afbc622017-11-27 09:42:17 -0800992 if (!get_dm_crypt_version(fd, name, version)) {
993 /* Support for allow_discards was added in version 1.11.0 */
994 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
995 extra_params_vec.emplace_back("allow_discards");
996 }
997 }
998 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
999 extra_params_vec.emplace_back("allow_encrypt_override");
1000 }
1001 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1002 extra_params_as_string(extra_params_vec).c_str());
1003 if (load_count < 0) {
1004 SLOGE("Cannot load dm-crypt mapping table.\n");
1005 goto errout;
1006 } else if (load_count > 1) {
1007 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1008 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001009
Paul Crowley5afbc622017-11-27 09:42:17 -08001010 /* Resume this device to activate it */
1011 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001012
Paul Crowley5afbc622017-11-27 09:42:17 -08001013 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1014 SLOGE("Cannot resume the dm-crypt device\n");
1015 goto errout;
1016 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001017
Paul Crowley5afbc622017-11-27 09:42:17 -08001018 /* We made it here with no errors. Woot! */
1019 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001020
1021errout:
1022 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1023
1024 return retval;
1025}
1026
Wei Wang4375f1b2017-02-24 17:43:01 -08001027static int delete_crypto_blk_dev(const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001028{
1029 int fd;
1030 char buffer[DM_CRYPT_BUF_SIZE];
1031 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001032 int retval = -1;
1033
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001034 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001035 SLOGE("Cannot open device-mapper\n");
1036 goto errout;
1037 }
1038
1039 io = (struct dm_ioctl *) buffer;
1040
1041 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1042 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1043 SLOGE("Cannot remove dm-crypt device\n");
1044 goto errout;
1045 }
1046
1047 /* We made it here with no errors. Woot! */
1048 retval = 0;
1049
1050errout:
1051 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1052
1053 return retval;
1054
1055}
1056
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001057static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001058 unsigned char *ikey, void *params UNUSED)
1059{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001060 SLOGI("Using pbkdf2 for cryptfs KDF");
1061
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001062 /* Turn the password into a key and IV that can decrypt the master key */
Adam Langleybf0d9722015-11-04 14:51:39 -08001063 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001064 HASH_COUNT, INTERMEDIATE_BUF_SIZE,
Adam Langleybf0d9722015-11-04 14:51:39 -08001065 ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001066}
1067
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001068static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001069 unsigned char *ikey, void *params)
1070{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001071 SLOGI("Using scrypt for cryptfs KDF");
1072
Kenny Rootc4c70f12013-06-14 12:11:38 -07001073 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1074
1075 int N = 1 << ftr->N_factor;
1076 int r = 1 << ftr->r_factor;
1077 int p = 1 << ftr->p_factor;
1078
1079 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001080 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1081 salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001082 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001083
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001084 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001085}
1086
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001087static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1088 unsigned char *ikey, void *params)
1089{
1090 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1091
1092 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001093 size_t signature_size;
1094 unsigned char* signature;
1095 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1096
1097 int N = 1 << ftr->N_factor;
1098 int r = 1 << ftr->r_factor;
1099 int p = 1 << ftr->p_factor;
1100
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001101 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1102 salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001103 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001104
1105 if (rc) {
1106 SLOGE("scrypt failed");
1107 return -1;
1108 }
1109
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001110 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE,
Shawn Willdene17a9c42014-09-08 13:04:08 -06001111 &signature, &signature_size)) {
1112 SLOGE("Signing failed");
1113 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001114 }
1115
1116 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001117 N, r, p, ikey, INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001118 free(signature);
1119
1120 if (rc) {
1121 SLOGE("scrypt failed");
1122 return -1;
1123 }
1124
1125 return 0;
1126}
1127
1128static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1129 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001130 unsigned char *encrypted_master_key,
1131 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001132{
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001133 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = { 0 };
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001134 EVP_CIPHER_CTX e_ctx;
1135 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001136 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001137
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001138 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001139 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001140
1141 switch (crypt_ftr->kdf_type) {
1142 case KDF_SCRYPT_KEYMASTER:
1143 if (keymaster_create_key(crypt_ftr)) {
1144 SLOGE("keymaster_create_key failed");
1145 return -1;
1146 }
1147
1148 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1149 SLOGE("scrypt failed");
1150 return -1;
1151 }
1152 break;
1153
1154 case KDF_SCRYPT:
1155 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1156 SLOGE("scrypt failed");
1157 return -1;
1158 }
1159 break;
1160
1161 default:
1162 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001163 return -1;
1164 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001165
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001166 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001167 EVP_CIPHER_CTX_init(&e_ctx);
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001168 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1169 ikey+INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001170 SLOGE("EVP_EncryptInit failed\n");
1171 return -1;
1172 }
1173 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001174
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001175 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001176 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Greg Kaiser59ad0182018-02-16 13:01:36 -08001177 decrypted_master_key, crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001178 SLOGE("EVP_EncryptUpdate failed\n");
1179 return -1;
1180 }
Adam Langley889c4f12014-09-03 14:23:13 -07001181 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001182 SLOGE("EVP_EncryptFinal failed\n");
1183 return -1;
1184 }
1185
Greg Kaiser59ad0182018-02-16 13:01:36 -08001186 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001187 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1188 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001189 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001190
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001191 /* Store the scrypt of the intermediate key, so we can validate if it's a
1192 password error or mount error when things go wrong.
1193 Note there's no need to check for errors, since if this is incorrect, we
1194 simply won't wipe userdata, which is the correct default behavior
1195 */
1196 int N = 1 << crypt_ftr->N_factor;
1197 int r = 1 << crypt_ftr->r_factor;
1198 int p = 1 << crypt_ftr->p_factor;
1199
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001200 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001201 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1202 crypt_ftr->scrypted_intermediate_key,
1203 sizeof(crypt_ftr->scrypted_intermediate_key));
1204
1205 if (rc) {
1206 SLOGE("encrypt_master_key: crypto_scrypt failed");
1207 }
1208
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001209 EVP_CIPHER_CTX_cleanup(&e_ctx);
1210
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001211 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001212}
1213
Paul Lawrence731a7a22015-04-28 22:14:15 +00001214static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Greg Kaiser59ad0182018-02-16 13:01:36 -08001215 const unsigned char *encrypted_master_key,
1216 size_t keysize,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001217 unsigned char *decrypted_master_key,
1218 kdf_func kdf, void *kdf_params,
1219 unsigned char** intermediate_key,
1220 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001221{
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001222 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = { 0 };
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001223 EVP_CIPHER_CTX d_ctx;
1224 int decrypted_len, final_len;
1225
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001226 /* Turn the password into an intermediate key and IV that can decrypt the
1227 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001228 if (kdf(passwd, salt, ikey, kdf_params)) {
1229 SLOGE("kdf failed");
1230 return -1;
1231 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001232
1233 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001234 EVP_CIPHER_CTX_init(&d_ctx);
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001235 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001236 return -1;
1237 }
1238 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1239 /* Decrypt the master key */
1240 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
Greg Kaiser59ad0182018-02-16 13:01:36 -08001241 encrypted_master_key, keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001242 return -1;
1243 }
Adam Langley889c4f12014-09-03 14:23:13 -07001244 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001245 return -1;
1246 }
1247
Greg Kaiser59ad0182018-02-16 13:01:36 -08001248 if (decrypted_len + final_len != static_cast<int>(keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001249 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001250 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001251
1252 /* Copy intermediate key if needed by params */
1253 if (intermediate_key && intermediate_key_size) {
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001254 *intermediate_key = (unsigned char*) malloc(INTERMEDIATE_KEY_LEN_BYTES);
Greg Kaisere8167af2016-04-20 10:50:15 -07001255 if (*intermediate_key) {
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001256 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1257 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001258 }
1259 }
1260
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001261 EVP_CIPHER_CTX_cleanup(&d_ctx);
1262
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001263 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001264}
1265
Kenny Rootc4c70f12013-06-14 12:11:38 -07001266static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001267{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001268 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001269 *kdf = scrypt_keymaster;
1270 *kdf_params = ftr;
1271 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001272 *kdf = scrypt;
1273 *kdf_params = ftr;
1274 } else {
1275 *kdf = pbkdf2;
1276 *kdf_params = NULL;
1277 }
1278}
1279
Paul Lawrence731a7a22015-04-28 22:14:15 +00001280static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001281 struct crypt_mnt_ftr *crypt_ftr,
1282 unsigned char** intermediate_key,
1283 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001284{
1285 kdf_func kdf;
1286 void *kdf_params;
1287 int ret;
1288
1289 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001290 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
Greg Kaiser59ad0182018-02-16 13:01:36 -08001291 crypt_ftr->keysize,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001292 decrypted_master_key, kdf, kdf_params,
1293 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001294 if (ret != 0) {
1295 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001296 }
1297
1298 return ret;
1299}
1300
Wei Wang4375f1b2017-02-24 17:43:01 -08001301static int create_encrypted_random_key(const char *passwd, unsigned char *master_key, unsigned char *salt,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001302 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001303 int fd;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001304 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001305
1306 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001307 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001308 read(fd, key_buf, sizeof(key_buf));
1309 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001310 close(fd);
1311
1312 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001313 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001314}
1315
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001316int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001317{
Greg Hackmann955653e2014-09-24 14:55:20 -07001318 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001319#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001320
1321 /* Now umount the tmpfs filesystem */
1322 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001323 if (umount(mountpoint) == 0) {
1324 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001325 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001326
1327 if (errno == EINVAL) {
1328 /* EINVAL is returned if the directory is not a mountpoint,
1329 * i.e. there is no filesystem mounted there. So just get out.
1330 */
1331 break;
1332 }
1333
1334 err = errno;
1335
1336 /* If allowed, be increasingly aggressive before the last two retries */
1337 if (kill) {
1338 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1339 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001340 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001341 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1342 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001343 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001344 }
1345 }
1346
1347 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001348 }
1349
1350 if (i < WAIT_UNMOUNT_COUNT) {
1351 SLOGD("unmounting %s succeeded\n", mountpoint);
1352 rc = 0;
1353 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001354 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001355 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001356 rc = -1;
1357 }
1358
1359 return rc;
1360}
1361
Wei Wang42e38102017-06-07 10:46:12 -07001362static void prep_data_fs(void)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001363{
Jeff Sharkey47695b22016-02-01 17:02:29 -07001364 // NOTE: post_fs_data results in init calling back around to vold, so all
1365 // callers to this method must be async
1366
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001367 /* Do the prep of the /data filesystem */
1368 property_set("vold.post_fs_data_done", "0");
1369 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001370 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001371
Ken Sumrallc5872692013-05-14 15:26:31 -07001372 /* Wait a max of 50 seconds, hopefully it takes much less */
Wei Wang42e38102017-06-07 10:46:12 -07001373 while (!android::base::WaitForProperty("vold.post_fs_data_done",
Wei Wang4375f1b2017-02-24 17:43:01 -08001374 "1",
Wei Wang42e38102017-06-07 10:46:12 -07001375 std::chrono::seconds(15))) {
1376 /* We timed out to prep /data in time. Continue wait. */
1377 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001378 }
Wei Wang42e38102017-06-07 10:46:12 -07001379 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001380}
1381
Paul Lawrence74f29f12014-08-28 15:54:10 -07001382static void cryptfs_set_corrupt()
1383{
1384 // Mark the footer as bad
1385 struct crypt_mnt_ftr crypt_ftr;
1386 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1387 SLOGE("Failed to get crypto footer - panic");
1388 return;
1389 }
1390
1391 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1392 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1393 SLOGE("Failed to set crypto footer - panic");
1394 return;
1395 }
1396}
1397
1398static void cryptfs_trigger_restart_min_framework()
1399{
1400 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1401 SLOGE("Failed to mount tmpfs on data - panic");
1402 return;
1403 }
1404
1405 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1406 SLOGE("Failed to trigger post fs data - panic");
1407 return;
1408 }
1409
1410 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1411 SLOGE("Failed to trigger restart min framework - panic");
1412 return;
1413 }
1414}
1415
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001416/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001417static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001418{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001419 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001420 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001421 static int restart_successful = 0;
1422
1423 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001424 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001425 SLOGE("Encrypted filesystem not validated, aborting");
1426 return -1;
1427 }
1428
1429 if (restart_successful) {
1430 SLOGE("System already restarted with encrypted disk, aborting");
1431 return -1;
1432 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001433
Paul Lawrencef4faa572014-01-29 13:31:03 -08001434 if (restart_main) {
1435 /* Here is where we shut down the framework. The init scripts
1436 * start all services in one of three classes: core, main or late_start.
1437 * On boot, we start core and main. Now, we stop main, but not core,
1438 * as core includes vold and a few other really important things that
1439 * we need to keep running. Once main has stopped, we should be able
1440 * to umount the tmpfs /data, then mount the encrypted /data.
1441 * We then restart the class main, and also the class late_start.
1442 * At the moment, I've only put a few things in late_start that I know
1443 * are not needed to bring up the framework, and that also cause problems
1444 * with unmounting the tmpfs /data, but I hope to add add more services
1445 * to the late_start class as we optimize this to decrease the delay
1446 * till the user is asked for the password to the filesystem.
1447 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001448
Paul Lawrencef4faa572014-01-29 13:31:03 -08001449 /* The init files are setup to stop the class main when vold.decrypt is
1450 * set to trigger_reset_main.
1451 */
1452 property_set("vold.decrypt", "trigger_reset_main");
1453 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001454
Paul Lawrencef4faa572014-01-29 13:31:03 -08001455 /* Ugh, shutting down the framework is not synchronous, so until it
1456 * can be fixed, this horrible hack will wait a moment for it all to
1457 * shut down before proceeding. Without it, some devices cannot
1458 * restart the graphics services.
1459 */
1460 sleep(2);
1461 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001462
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001463 /* Now that the framework is shutdown, we should be able to umount()
1464 * the tmpfs filesystem, and mount the real one.
1465 */
1466
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001467 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1468 if (strlen(crypto_blkdev) == 0) {
1469 SLOGE("fs_crypto_blkdev not set\n");
1470 return -1;
1471 }
1472
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001473 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001474 /* If ro.crypto.readonly is set to 1, mount the decrypted
1475 * filesystem readonly. This is used when /data is mounted by
1476 * recovery mode.
1477 */
1478 char ro_prop[PROPERTY_VALUE_MAX];
1479 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001480 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001481 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Doug Zongker6fd57712013-12-17 09:43:23 -08001482 rec->flags |= MS_RDONLY;
1483 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001484
Ken Sumralle5032c42012-04-01 23:58:44 -07001485 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001486 int retries = RETRY_MOUNT_ATTEMPTS;
1487 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001488
1489 /*
1490 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1491 * partitions in the fsck domain.
1492 */
1493 if (setexeccon(secontextFsck())){
1494 SLOGE("Failed to setexeccon");
1495 return -1;
1496 }
Paul Crowleye2ee1522017-09-26 14:05:26 -07001497 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT,
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001498 crypto_blkdev, 0))
1499 != 0) {
1500 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1501 /* TODO: invoke something similar to
1502 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1503 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1504 SLOGI("Failed to mount %s because it is busy - waiting",
1505 crypto_blkdev);
1506 if (--retries) {
1507 sleep(RETRY_MOUNT_DELAY_SECONDS);
1508 } else {
1509 /* Let's hope that a reboot clears away whatever is keeping
1510 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001511 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001512 }
1513 } else {
1514 SLOGE("Failed to mount decrypted data");
1515 cryptfs_set_corrupt();
1516 cryptfs_trigger_restart_min_framework();
1517 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001518 if (setexeccon(NULL)) {
1519 SLOGE("Failed to setexeccon");
1520 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001521 return -1;
1522 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001523 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001524 if (setexeccon(NULL)) {
1525 SLOGE("Failed to setexeccon");
1526 return -1;
1527 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001528
Ken Sumralle5032c42012-04-01 23:58:44 -07001529 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001530 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001531 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001532
1533 /* startup service classes main and late_start */
1534 property_set("vold.decrypt", "trigger_restart_framework");
1535 SLOGD("Just triggered restart_framework\n");
1536
1537 /* Give it a few moments to get started */
1538 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001539 }
1540
Ken Sumrall0cc16632011-01-18 20:32:26 -08001541 if (rc == 0) {
1542 restart_successful = 1;
1543 }
1544
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001545 return rc;
1546}
1547
Paul Lawrencef4faa572014-01-29 13:31:03 -08001548int cryptfs_restart(void)
1549{
Paul Lawrence05335c32015-03-05 09:46:23 -08001550 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001551 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001552 SLOGE("cryptfs_restart not valid for file encryption:");
1553 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001554 }
1555
Paul Lawrencef4faa572014-01-29 13:31:03 -08001556 /* Call internal implementation forcing a restart of main service group */
1557 return cryptfs_restart_internal(1);
1558}
1559
Wei Wang4375f1b2017-02-24 17:43:01 -08001560static int do_crypto_complete(const char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001561{
1562 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001563 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001564 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001565
1566 property_get("ro.crypto.state", encrypted_state, "");
1567 if (strcmp(encrypted_state, "encrypted") ) {
1568 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001569 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001570 }
1571
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001572 // crypto_complete is full disk encrypted status
Paul Crowley38132a12016-02-09 09:50:32 +00001573 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001574 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Paul Lawrence05335c32015-03-05 09:46:23 -08001575 }
1576
Ken Sumrall160b4d62013-04-22 12:15:39 -07001577 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001578 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001579
Ken Sumralle1a45852011-12-14 21:24:27 -08001580 /*
1581 * Only report this error if key_loc is a file and it exists.
1582 * If the device was never encrypted, and /data is not mountable for
1583 * some reason, returning 1 should prevent the UI from presenting the
1584 * a "enter password" screen, or worse, a "press button to wipe the
1585 * device" screen.
1586 */
1587 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1588 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001589 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001590 } else {
1591 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001592 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001593 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001594 }
1595
Paul Lawrence74f29f12014-08-28 15:54:10 -07001596 // Test for possible error flags
1597 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1598 SLOGE("Encryption process is partway completed\n");
1599 return CRYPTO_COMPLETE_PARTIAL;
1600 }
1601
1602 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1603 SLOGE("Encryption process was interrupted but cannot continue\n");
1604 return CRYPTO_COMPLETE_INCONSISTENT;
1605 }
1606
1607 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1608 SLOGE("Encryption is successful but data is corrupt\n");
1609 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001610 }
1611
1612 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001613 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001614}
1615
Paul Lawrencef4faa572014-01-29 13:31:03 -08001616static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
Wei Wang4375f1b2017-02-24 17:43:01 -08001617 const char *passwd, const char *mount_point, const char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001618{
Greg Kaiser59ad0182018-02-16 13:01:36 -08001619 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001620 char crypto_blkdev[MAXPATHLEN];
1621 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001622 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001623 unsigned int orig_failed_decrypt_count;
1624 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001625 int use_keymaster = 0;
1626 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001627 unsigned char* intermediate_key = 0;
1628 size_t intermediate_key_size = 0;
Wei Wang4375f1b2017-02-24 17:43:01 -08001629 int N = 1 << crypt_ftr->N_factor;
1630 int r = 1 << crypt_ftr->r_factor;
1631 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001632
Paul Lawrencef4faa572014-01-29 13:31:03 -08001633 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1634 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001635
Paul Lawrencef4faa572014-01-29 13:31:03 -08001636 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001637 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1638 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001639 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001640 rc = -1;
1641 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001642 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001643 }
1644
Paul Crowleye2ee1522017-09-26 14:05:26 -07001645 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Paul Lawrencef4faa572014-01-29 13:31:03 -08001646
Paul Lawrence74f29f12014-08-28 15:54:10 -07001647 // Create crypto block device - all (non fatal) code paths
1648 // need it
Paul Crowley5afbc622017-11-27 09:42:17 -08001649 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label, 0)) {
1650 SLOGE("Error creating decrypted block device\n");
1651 rc = -1;
1652 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001653 }
1654
Paul Lawrence74f29f12014-08-28 15:54:10 -07001655 /* Work out if the problem is the password or the data */
1656 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1657 scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001658
Paul Lawrence74f29f12014-08-28 15:54:10 -07001659 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1660 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1661 N, r, p, scrypted_intermediate_key,
1662 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001663
Paul Lawrence74f29f12014-08-28 15:54:10 -07001664 // Does the key match the crypto footer?
1665 if (rc == 0 && memcmp(scrypted_intermediate_key,
1666 crypt_ftr->scrypted_intermediate_key,
1667 sizeof(scrypted_intermediate_key)) == 0) {
1668 SLOGI("Password matches");
1669 rc = 0;
1670 } else {
1671 /* Try mounting the file system anyway, just in case the problem's with
1672 * the footer, not the key. */
George Burgess IV605d7ae2016-02-29 13:39:17 -08001673 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt",
1674 mount_point);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001675 mkdir(tmp_mount_point, 0755);
Paul Crowleye2ee1522017-09-26 14:05:26 -07001676 if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001677 SLOGE("Error temp mounting decrypted block device\n");
1678 delete_crypto_blk_dev(label);
1679
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001680 rc = ++crypt_ftr->failed_decrypt_count;
1681 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001682 } else {
1683 /* Success! */
1684 SLOGI("Password did not match but decrypted drive mounted - continue");
1685 umount(tmp_mount_point);
1686 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001687 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001688 }
1689
1690 if (rc == 0) {
1691 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001692 if (orig_failed_decrypt_count != 0) {
1693 put_crypt_ftr_and_key(crypt_ftr);
1694 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001695
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001696 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001697 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001698 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001699
1700 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001701 * the key when we want to change the password on it. */
Greg Kaiser59ad0182018-02-16 13:01:36 -08001702 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001703 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001704 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001705 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001706 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001707
Paul Lawrence74f29f12014-08-28 15:54:10 -07001708 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001709 use_keymaster = keymaster_check_compatibility();
1710 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001711 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001712 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1713 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1714 upgrade = 1;
1715 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001716 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001717 upgrade = 1;
1718 }
1719
1720 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001721 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1722 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001723 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001724 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001725 }
1726 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001727
1728 // Do not fail even if upgrade failed - machine is bootable
1729 // Note that if this code is ever hit, there is a *serious* problem
1730 // since KDFs should never fail. You *must* fix the kdf before
1731 // proceeding!
1732 if (rc) {
1733 SLOGW("Upgrade failed with error %d,"
1734 " but continuing with previous state",
1735 rc);
1736 rc = 0;
1737 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001738 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001739 }
1740
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001741 errout:
1742 if (intermediate_key) {
1743 memset(intermediate_key, 0, intermediate_key_size);
1744 free(intermediate_key);
1745 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001746 return rc;
1747}
1748
Ken Sumrall29d8da82011-05-18 17:20:07 -07001749/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001750 * Called by vold when it's asked to mount an encrypted external
1751 * storage volume. The incoming partition has no crypto header/footer,
1752 * as any metadata is been stored in a separate, small partition.
1753 *
1754 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001755 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001756int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1757 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001758 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001759 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001760 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001761 return -1;
1762 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08001763 if (keysize > MAX_KEY_LEN) {
1764 SLOGE("ext_volume keysize (%d) larger than max (%d)\n", keysize,
1765 MAX_KEY_LEN);
1766 return -1;
1767 }
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001768
1769 unsigned long nr_sec = 0;
1770 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001771 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001772
Ken Sumrall29d8da82011-05-18 17:20:07 -07001773 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001774 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001775 return -1;
1776 }
1777
Jeff Sharkey9c484982015-03-31 10:35:33 -07001778 struct crypt_mnt_ftr ext_crypt_ftr;
1779 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1780 ext_crypt_ftr.fs_size = nr_sec;
1781 ext_crypt_ftr.keysize = keysize;
Greg Kaiserfa099612018-02-14 11:26:00 -08001782 strlcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256",
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001783 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001784
Paul Crowley5afbc622017-11-27 09:42:17 -08001785 return create_crypto_blk_dev(
1786 &ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label,
1787 e4crypt_is_native() ? CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE : 0);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001788}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001789
Jeff Sharkey9c484982015-03-31 10:35:33 -07001790/*
1791 * Called by vold when it's asked to unmount an encrypted external
1792 * storage volume.
1793 */
1794int cryptfs_revert_ext_volume(const char* label) {
1795 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001796}
1797
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001798int cryptfs_crypto_complete(void)
1799{
1800 return do_crypto_complete("/data");
1801}
1802
Paul Lawrencef4faa572014-01-29 13:31:03 -08001803int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1804{
1805 char encrypted_state[PROPERTY_VALUE_MAX];
1806 property_get("ro.crypto.state", encrypted_state, "");
1807 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1808 SLOGE("encrypted fs already validated or not running with encryption,"
1809 " aborting");
1810 return -1;
1811 }
1812
1813 if (get_crypt_ftr_and_key(crypt_ftr)) {
1814 SLOGE("Error getting crypt footer and key");
1815 return -1;
1816 }
1817
1818 return 0;
1819}
1820
Wei Wang4375f1b2017-02-24 17:43:01 -08001821int cryptfs_check_passwd(const char *passwd)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001822{
Paul Lawrence05335c32015-03-05 09:46:23 -08001823 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00001824 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001825 SLOGE("cryptfs_check_passwd not valid for file encryption");
1826 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001827 }
1828
Paul Lawrencef4faa572014-01-29 13:31:03 -08001829 struct crypt_mnt_ftr crypt_ftr;
1830 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001831
Paul Lawrencef4faa572014-01-29 13:31:03 -08001832 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001833 if (rc) {
1834 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001835 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001836 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001837
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001838 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001839 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1840 if (rc) {
1841 SLOGE("Password did not match");
1842 return rc;
1843 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001844
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001845 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1846 // Here we have a default actual password but a real password
1847 // we must test against the scrypted value
1848 // First, we must delete the crypto block device that
1849 // test_mount_encrypted_fs leaves behind as a side effect
1850 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
1851 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
1852 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1853 if (rc) {
1854 SLOGE("Default password did not match on reboot encryption");
1855 return rc;
1856 }
1857
1858 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1859 put_crypt_ftr_and_key(&crypt_ftr);
1860 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1861 if (rc) {
1862 SLOGE("Could not change password on reboot encryption");
1863 return rc;
1864 }
1865 }
1866
1867 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001868 cryptfs_clear_password();
1869 password = strdup(passwd);
1870 struct timespec now;
1871 clock_gettime(CLOCK_BOOTTIME, &now);
1872 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001873 }
1874
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001875 return rc;
1876}
1877
Jeff Sharkey83b559c2017-09-12 16:30:52 -06001878int cryptfs_verify_passwd(const char *passwd)
Ken Sumrall3ad90722011-10-04 20:38:29 -07001879{
1880 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001881 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001882 char encrypted_state[PROPERTY_VALUE_MAX];
1883 int rc;
1884
1885 property_get("ro.crypto.state", encrypted_state, "");
1886 if (strcmp(encrypted_state, "encrypted") ) {
1887 SLOGE("device not encrypted, aborting");
1888 return -2;
1889 }
1890
1891 if (!master_key_saved) {
1892 SLOGE("encrypted fs not yet mounted, aborting");
1893 return -1;
1894 }
1895
1896 if (!saved_mount_point) {
1897 SLOGE("encrypted fs failed to save mount point, aborting");
1898 return -1;
1899 }
1900
Ken Sumrall160b4d62013-04-22 12:15:39 -07001901 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001902 SLOGE("Error getting crypt footer and key\n");
1903 return -1;
1904 }
1905
1906 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1907 /* If the device has no password, then just say the password is valid */
1908 rc = 0;
1909 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001910 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001911 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1912 /* They match, the password is correct */
1913 rc = 0;
1914 } else {
1915 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1916 sleep(1);
1917 rc = 1;
1918 }
1919 }
1920
1921 return rc;
1922}
1923
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001924/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser59ad0182018-02-16 13:01:36 -08001925 * defaulted to DEFAULT_KEY_LEN_BYTES bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001926 * Presumably, at a minimum, the caller will update the
1927 * filesystem size and crypto_type_name after calling this function.
1928 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001929static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001930{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001931 off64_t off;
1932
1933 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001934 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001935 ftr->major_version = CURRENT_MAJOR_VERSION;
1936 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001937 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser59ad0182018-02-16 13:01:36 -08001938 ftr->keysize = DEFAULT_KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001939
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001940 switch (keymaster_check_compatibility()) {
1941 case 1:
1942 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1943 break;
1944
1945 case 0:
1946 ftr->kdf_type = KDF_SCRYPT;
1947 break;
1948
1949 default:
1950 SLOGE("keymaster_check_compatibility failed");
1951 return -1;
1952 }
1953
Kenny Rootc4c70f12013-06-14 12:11:38 -07001954 get_device_scrypt_params(ftr);
1955
Ken Sumrall160b4d62013-04-22 12:15:39 -07001956 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1957 if (get_crypt_ftr_info(NULL, &off) == 0) {
1958 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1959 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1960 ftr->persist_data_size;
1961 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001962
1963 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001964}
1965
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001966#define FRAMEWORK_BOOT_WAIT 60
1967
Paul Lawrence87999172014-02-20 12:21:31 -08001968static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
1969{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001970 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08001971 if (fd == -1) {
1972 SLOGE("Error opening file %s", filename);
1973 return -1;
1974 }
1975
1976 char block[CRYPT_INPLACE_BUFSIZE];
1977 memset(block, 0, sizeof(block));
1978 if (unix_read(fd, block, sizeof(block)) < 0) {
1979 SLOGE("Error reading file %s", filename);
1980 close(fd);
1981 return -1;
1982 }
1983
1984 close(fd);
1985
1986 SHA256_CTX c;
1987 SHA256_Init(&c);
1988 SHA256_Update(&c, block, sizeof(block));
1989 SHA256_Final(buf, &c);
1990
1991 return 0;
1992}
1993
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001994static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
1995 char* real_blkdev, int previously_encrypted_upto) {
Paul Lawrence87999172014-02-20 12:21:31 -08001996 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08001997 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08001998
Paul Lawrence87999172014-02-20 12:21:31 -08001999 /* The size of the userdata partition, and add in the vold volumes below */
2000 tot_encryption_size = crypt_ftr->fs_size;
2001
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002002 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002003 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002004
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002005 if (rc == ENABLE_INPLACE_ERR_DEV) {
2006 /* Hack for b/17898962 */
2007 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2008 cryptfs_reboot(RebootType::reboot);
2009 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002010
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002011 if (!rc) {
2012 crypt_ftr->encrypted_upto = cur_encryption_done;
2013 }
Paul Lawrence87999172014-02-20 12:21:31 -08002014
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002015 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2016 /* The inplace routine never actually sets the progress to 100% due
2017 * to the round down nature of integer division, so set it here */
2018 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002019 }
2020
2021 return rc;
2022}
2023
Paul Crowleyb64933a2017-10-31 08:25:55 -07002024static int vold_unmountAll(void) {
2025 VolumeManager* vm = VolumeManager::Instance();
2026 return vm->unmountAll();
2027}
2028
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002029int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Lawrence87999172014-02-20 12:21:31 -08002030 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Greg Kaiser59ad0182018-02-16 13:01:36 -08002031 unsigned char decrypted_master_key[MAX_KEY_LEN];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002032 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002033 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002034 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002035 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002036 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002037 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002038 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002039 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002040 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002041 bool onlyCreateHeader = false;
2042 int fd = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002043
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002044 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002045 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2046 /* An encryption was underway and was interrupted */
2047 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2048 crypt_ftr.encrypted_upto = 0;
2049 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002050
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002051 /* At this point, we are in an inconsistent state. Until we successfully
2052 complete encryption, a reboot will leave us broken. So mark the
2053 encryption failed in case that happens.
2054 On successfully completing encryption, remove this flag */
2055 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002056
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002057 put_crypt_ftr_and_key(&crypt_ftr);
2058 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2059 if (!check_ftr_sha(&crypt_ftr)) {
2060 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2061 put_crypt_ftr_and_key(&crypt_ftr);
2062 goto error_unencrypted;
2063 }
2064
2065 /* Doing a reboot-encryption*/
2066 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2067 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2068 rebootEncryption = true;
2069 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002070 } else {
2071 // We don't want to accidentally reference invalid data.
2072 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002073 }
2074
2075 property_get("ro.crypto.state", encrypted_state, "");
2076 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2077 SLOGE("Device is already running encrypted, aborting");
2078 goto error_unencrypted;
2079 }
2080
2081 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002082 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2083 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002084
Ken Sumrall3ed82362011-01-28 23:31:16 -08002085 /* Get the size of the real block device */
Wei Wang4375f1b2017-02-24 17:43:01 -08002086 fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002087 if (fd == -1) {
2088 SLOGE("Cannot open block device %s\n", real_blkdev);
2089 goto error_unencrypted;
2090 }
2091 unsigned long nr_sec;
2092 get_blkdev_size(fd, &nr_sec);
2093 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002094 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2095 goto error_unencrypted;
2096 }
2097 close(fd);
2098
2099 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002100 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002101 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002102 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002103 if (fs_size_sec == 0)
2104 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2105
Paul Lawrence87999172014-02-20 12:21:31 -08002106 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002107
2108 if (fs_size_sec > max_fs_size_sec) {
2109 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2110 goto error_unencrypted;
2111 }
2112 }
2113
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002114 /* Get a wakelock as this may take a while, and we don't want the
2115 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2116 * wants to keep the screen on, it can grab a full wakelock.
2117 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002118 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002119 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2120
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002121 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002122 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002123 */
2124 property_set("vold.decrypt", "trigger_shutdown_framework");
2125 SLOGD("Just asked init to shut down class main\n");
2126
Jeff Sharkey9c484982015-03-31 10:35:33 -07002127 /* Ask vold to unmount all devices that it manages */
2128 if (vold_unmountAll()) {
2129 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002130 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002131
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002132 /* no_ui means we are being called from init, not settings.
2133 Now we always reboot from settings, so !no_ui means reboot
2134 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002135 if (!no_ui) {
2136 /* Try fallback, which is to reboot and try there */
2137 onlyCreateHeader = true;
2138 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2139 if (breadcrumb == 0) {
2140 SLOGE("Failed to create breadcrumb file");
2141 goto error_shutting_down;
2142 }
2143 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002144 }
2145
2146 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002147 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002148 /* Now that /data is unmounted, we need to mount a tmpfs
2149 * /data, set a property saying we're doing inplace encryption,
2150 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002151 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002152 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002153 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002154 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002155 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002156 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002157
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002158 /* restart the framework. */
2159 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002160 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002161
Ken Sumrall92736ef2012-10-17 20:57:14 -07002162 /* Ugh, shutting down the framework is not synchronous, so until it
2163 * can be fixed, this horrible hack will wait a moment for it all to
2164 * shut down before proceeding. Without it, some devices cannot
2165 * restart the graphics services.
2166 */
2167 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002168 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002169
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002170 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002171 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002172 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002173 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2174 goto error_shutting_down;
2175 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002176
Paul Lawrence87999172014-02-20 12:21:31 -08002177 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2178 crypt_ftr.fs_size = nr_sec
2179 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2180 } else {
2181 crypt_ftr.fs_size = nr_sec;
2182 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002183 /* At this point, we are in an inconsistent state. Until we successfully
2184 complete encryption, a reboot will leave us broken. So mark the
2185 encryption failed in case that happens.
2186 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002187 if (onlyCreateHeader) {
2188 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2189 } else {
2190 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2191 }
Paul Lawrence87999172014-02-20 12:21:31 -08002192 crypt_ftr.crypt_type = crypt_type;
Greg Kaiserfa099612018-02-14 11:26:00 -08002193 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002194
Paul Lawrence87999172014-02-20 12:21:31 -08002195 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002196 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2197 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002198 SLOGE("Cannot create encrypted master key\n");
2199 goto error_shutting_down;
2200 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002201
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002202 /* Replace scrypted intermediate key if we are preparing for a reboot */
2203 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002204 unsigned char fake_master_key[MAX_KEY_LEN];
2205 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002206 memset(fake_master_key, 0, sizeof(fake_master_key));
2207 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
2208 encrypted_fake_master_key, &crypt_ftr);
2209 }
2210
Paul Lawrence87999172014-02-20 12:21:31 -08002211 /* Write the key to the end of the partition */
2212 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002213
Paul Lawrence87999172014-02-20 12:21:31 -08002214 /* If any persistent data has been remembered, save it.
2215 * If none, create a valid empty table and save that.
2216 */
2217 if (!persist_data) {
Wei Wang4375f1b2017-02-24 17:43:01 -08002218 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002219 if (pdata) {
2220 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2221 persist_data = pdata;
2222 }
2223 }
2224 if (persist_data) {
2225 save_persistent_data();
2226 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002227 }
2228
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002229 if (onlyCreateHeader) {
2230 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002231 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002232 }
2233
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002234 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002235 /* startup service classes main and late_start */
2236 property_set("vold.decrypt", "trigger_restart_min_framework");
2237 SLOGD("Just triggered restart_min_framework\n");
2238
2239 /* OK, the framework is restarted and will soon be showing a
2240 * progress bar. Time to setup an encrypted mapping, and
2241 * either write a new filesystem, or encrypt in place updating
2242 * the progress bar as we work.
2243 */
2244 }
2245
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002246 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002247 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002248 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002249
Paul Lawrence87999172014-02-20 12:21:31 -08002250 /* If we are continuing, check checksums match */
2251 rc = 0;
2252 if (previously_encrypted_upto) {
2253 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2254 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002255
Paul Lawrence87999172014-02-20 12:21:31 -08002256 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2257 sizeof(hash_first_block)) != 0) {
2258 SLOGE("Checksums do not match - trigger wipe");
2259 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002260 }
2261 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002262
Paul Lawrence87999172014-02-20 12:21:31 -08002263 if (!rc) {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002264 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002265 previously_encrypted_upto);
2266 }
2267
2268 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002269 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002270 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2271 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002272 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002273 SLOGE("Error calculating checksum for continuing encryption");
2274 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002275 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002276 }
2277
2278 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002279 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002280
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002281 if (! rc) {
2282 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002283 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002284
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002285 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002286 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2287 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002288 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002289 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002290
Paul Lawrence6bfed202014-07-28 12:47:22 -07002291 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002292
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002293 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2294 char value[PROPERTY_VALUE_MAX];
2295 property_get("ro.crypto.state", value, "");
2296 if (!strcmp(value, "")) {
2297 /* default encryption - continue first boot sequence */
2298 property_set("ro.crypto.state", "encrypted");
2299 property_set("ro.crypto.type", "block");
2300 release_wake_lock(lockid);
2301 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2302 // Bring up cryptkeeper that will check the password and set it
2303 property_set("vold.decrypt", "trigger_shutdown_framework");
2304 sleep(2);
2305 property_set("vold.encrypt_progress", "");
2306 cryptfs_trigger_restart_min_framework();
2307 } else {
2308 cryptfs_check_passwd(DEFAULT_PASSWORD);
2309 cryptfs_restart_internal(1);
2310 }
2311 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002312 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002313 sleep(2); /* Give the UI a chance to show 100% progress */
2314 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002315 }
Paul Lawrence87999172014-02-20 12:21:31 -08002316 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002317 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002318 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002319 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002320 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002321 char value[PROPERTY_VALUE_MAX];
2322
Ken Sumrall319369a2012-06-27 16:30:18 -07002323 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002324 if (!strcmp(value, "1")) {
2325 /* wipe data if encryption failed */
2326 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002327 std::string err;
2328 const std::vector<std::string> options = {
2329 "--wipe_data\n--reason=cryptfs_enable_internal\n"
2330 };
2331 if (!write_bootloader_message(options, &err)) {
2332 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002333 }
Josh Gaofec44372017-08-28 13:22:55 -07002334 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002335 } else {
2336 /* set property to trigger dialog */
2337 property_set("vold.encrypt_progress", "error_partially_encrypted");
2338 release_wake_lock(lockid);
2339 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002340 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002341 }
2342
Ken Sumrall3ed82362011-01-28 23:31:16 -08002343 /* hrm, the encrypt step claims success, but the reboot failed.
2344 * This should not happen.
2345 * Set the property and return. Hope the framework can deal with it.
2346 */
2347 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002348 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002349 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002350
2351error_unencrypted:
2352 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002353 if (lockid[0]) {
2354 release_wake_lock(lockid);
2355 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002356 return -1;
2357
2358error_shutting_down:
2359 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2360 * but the framework is stopped and not restarted to show the error, so it's up to
2361 * vold to restart the system.
2362 */
2363 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Josh Gaofec44372017-08-28 13:22:55 -07002364 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002365
2366 /* shouldn't get here */
2367 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002368 if (lockid[0]) {
2369 release_wake_lock(lockid);
2370 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002371 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002372}
2373
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002374int cryptfs_enable(int type, const char* passwd, int no_ui) {
2375 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002376}
2377
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002378int cryptfs_enable_default(int no_ui) {
2379 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002380}
2381
2382int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002383{
Paul Crowley38132a12016-02-09 09:50:32 +00002384 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002385 SLOGE("cryptfs_changepw not valid for file encryption");
2386 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002387 }
2388
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002389 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002390 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002391
2392 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002393 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002394 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002395 return -1;
2396 }
2397
Paul Lawrencef4faa572014-01-29 13:31:03 -08002398 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2399 SLOGE("Invalid crypt_type %d", crypt_type);
2400 return -1;
2401 }
2402
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002403 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002404 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002405 SLOGE("Error getting crypt footer and key");
2406 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002407 }
2408
Paul Lawrencef4faa572014-01-29 13:31:03 -08002409 crypt_ftr.crypt_type = crypt_type;
2410
JP Abgrall933216c2015-02-11 13:44:32 -08002411 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08002412 : newpw,
2413 crypt_ftr.salt,
2414 saved_master_key,
2415 crypt_ftr.master_key,
2416 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002417 if (rc) {
2418 SLOGE("Encrypt master key failed: %d", rc);
2419 return -1;
2420 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002421 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002422 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002423
2424 return 0;
2425}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002426
Rubin Xu85c01f92014-10-13 12:49:54 +01002427static unsigned int persist_get_max_entries(int encrypted) {
2428 struct crypt_mnt_ftr crypt_ftr;
2429 unsigned int dsize;
2430 unsigned int max_persistent_entries;
2431
2432 /* If encrypted, use the values from the crypt_ftr, otherwise
2433 * use the values for the current spec.
2434 */
2435 if (encrypted) {
2436 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2437 return -1;
2438 }
2439 dsize = crypt_ftr.persist_data_size;
2440 } else {
2441 dsize = CRYPT_PERSIST_DATA_SIZE;
2442 }
2443
2444 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2445 sizeof(struct crypt_persist_entry);
2446
2447 return max_persistent_entries;
2448}
2449
2450static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002451{
2452 unsigned int i;
2453
2454 if (persist_data == NULL) {
2455 return -1;
2456 }
2457 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2458 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2459 /* We found it! */
2460 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2461 return 0;
2462 }
2463 }
2464
2465 return -1;
2466}
2467
Rubin Xu85c01f92014-10-13 12:49:54 +01002468static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002469{
2470 unsigned int i;
2471 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002472 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002473
2474 if (persist_data == NULL) {
2475 return -1;
2476 }
2477
Rubin Xu85c01f92014-10-13 12:49:54 +01002478 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002479
2480 num = persist_data->persist_valid_entries;
2481
2482 for (i = 0; i < num; i++) {
2483 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2484 /* We found an existing entry, update it! */
2485 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2486 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2487 return 0;
2488 }
2489 }
2490
2491 /* We didn't find it, add it to the end, if there is room */
2492 if (persist_data->persist_valid_entries < max_persistent_entries) {
2493 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2494 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2495 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2496 persist_data->persist_valid_entries++;
2497 return 0;
2498 }
2499
2500 return -1;
2501}
2502
Rubin Xu85c01f92014-10-13 12:49:54 +01002503/**
2504 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2505 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2506 */
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002507int match_multi_entry(const char *key, const char *field, unsigned index) {
2508 std::string key_ = key;
2509 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002510
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002511 std::string parsed_field;
2512 unsigned parsed_index;
2513
2514 std::string::size_type split = key_.find_last_of('_');
2515 if (split == std::string::npos) {
2516 parsed_field = key_;
2517 parsed_index = 0;
2518 } else {
2519 parsed_field = key_.substr(0, split);
2520 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002521 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002522
2523 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002524}
2525
2526/*
2527 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2528 * remaining entries starting from index will be deleted.
2529 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2530 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2531 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2532 *
2533 */
2534static int persist_del_keys(const char *fieldname, unsigned index)
2535{
2536 unsigned int i;
2537 unsigned int j;
2538 unsigned int num;
2539
2540 if (persist_data == NULL) {
2541 return PERSIST_DEL_KEY_ERROR_OTHER;
2542 }
2543
2544 num = persist_data->persist_valid_entries;
2545
2546 j = 0; // points to the end of non-deleted entries.
2547 // Filter out to-be-deleted entries in place.
2548 for (i = 0; i < num; i++) {
2549 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2550 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2551 j++;
2552 }
2553 }
2554
2555 if (j < num) {
2556 persist_data->persist_valid_entries = j;
2557 // Zeroise the remaining entries
2558 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2559 return PERSIST_DEL_KEY_OK;
2560 } else {
2561 // Did not find an entry matching the given fieldname
2562 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2563 }
2564}
2565
2566static int persist_count_keys(const char *fieldname)
2567{
2568 unsigned int i;
2569 unsigned int count;
2570
2571 if (persist_data == NULL) {
2572 return -1;
2573 }
2574
2575 count = 0;
2576 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2577 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2578 count++;
2579 }
2580 }
2581
2582 return count;
2583}
2584
Ken Sumrall160b4d62013-04-22 12:15:39 -07002585/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002586int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002587{
Paul Crowley38132a12016-02-09 09:50:32 +00002588 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002589 SLOGE("Cannot get field when file encrypted");
2590 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002591 }
2592
Ken Sumrall160b4d62013-04-22 12:15:39 -07002593 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002594 /* CRYPTO_GETFIELD_OK is success,
2595 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2596 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2597 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002598 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002599 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2600 int i;
2601 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002602
2603 if (persist_data == NULL) {
2604 load_persistent_data();
2605 if (persist_data == NULL) {
2606 SLOGE("Getfield error, cannot load persistent data");
2607 goto out;
2608 }
2609 }
2610
Rubin Xu85c01f92014-10-13 12:49:54 +01002611 // Read value from persistent entries. If the original value is split into multiple entries,
2612 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002613 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002614 // We found it, copy it to the caller's buffer and keep going until all entries are read.
2615 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
2616 // value too small
2617 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2618 goto out;
2619 }
2620 rc = CRYPTO_GETFIELD_OK;
2621
2622 for (i = 1; /* break explicitly */; i++) {
2623 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
2624 (int) sizeof(temp_field)) {
2625 // If the fieldname is very long, we stop as soon as it begins to overflow the
2626 // maximum field length. At this point we have in fact fully read out the original
2627 // value because cryptfs_setfield would not allow fields with longer names to be
2628 // written in the first place.
2629 break;
2630 }
2631 if (!persist_get_key(temp_field, temp_value)) {
2632 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2633 // value too small.
2634 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2635 goto out;
2636 }
2637 } else {
2638 // Exhaust all entries.
2639 break;
2640 }
2641 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002642 } else {
2643 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002644 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002645 }
2646
2647out:
2648 return rc;
2649}
2650
2651/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002652int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002653{
Paul Crowley38132a12016-02-09 09:50:32 +00002654 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002655 SLOGE("Cannot set field when file encrypted");
2656 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002657 }
2658
Ken Sumrall160b4d62013-04-22 12:15:39 -07002659 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002660 /* 0 is success, negative values are error */
2661 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002662 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002663 unsigned int field_id;
2664 char temp_field[PROPERTY_KEY_MAX];
2665 unsigned int num_entries;
2666 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002667
2668 if (persist_data == NULL) {
2669 load_persistent_data();
2670 if (persist_data == NULL) {
2671 SLOGE("Setfield error, cannot load persistent data");
2672 goto out;
2673 }
2674 }
2675
2676 property_get("ro.crypto.state", encrypted_state, "");
2677 if (!strcmp(encrypted_state, "encrypted") ) {
2678 encrypted = 1;
2679 }
2680
Rubin Xu85c01f92014-10-13 12:49:54 +01002681 // Compute the number of entries required to store value, each entry can store up to
2682 // (PROPERTY_VALUE_MAX - 1) chars
2683 if (strlen(value) == 0) {
2684 // Empty value also needs one entry to store.
2685 num_entries = 1;
2686 } else {
2687 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2688 }
2689
2690 max_keylen = strlen(fieldname);
2691 if (num_entries > 1) {
2692 // Need an extra "_%d" suffix.
2693 max_keylen += 1 + log10(num_entries);
2694 }
2695 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2696 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002697 goto out;
2698 }
2699
Rubin Xu85c01f92014-10-13 12:49:54 +01002700 // Make sure we have enough space to write the new value
2701 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2702 persist_get_max_entries(encrypted)) {
2703 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2704 goto out;
2705 }
2706
2707 // Now that we know persist_data has enough space for value, let's delete the old field first
2708 // to make up space.
2709 persist_del_keys(fieldname, 0);
2710
2711 if (persist_set_key(fieldname, value, encrypted)) {
2712 // fail to set key, should not happen as we have already checked the available space
2713 SLOGE("persist_set_key() error during setfield()");
2714 goto out;
2715 }
2716
2717 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002718 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002719
2720 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2721 // fail to set key, should not happen as we have already checked the available space.
2722 SLOGE("persist_set_key() error during setfield()");
2723 goto out;
2724 }
2725 }
2726
Ken Sumrall160b4d62013-04-22 12:15:39 -07002727 /* If we are running encrypted, save the persistent data now */
2728 if (encrypted) {
2729 if (save_persistent_data()) {
2730 SLOGE("Setfield error, cannot save persistent data");
2731 goto out;
2732 }
2733 }
2734
Rubin Xu85c01f92014-10-13 12:49:54 +01002735 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002736
2737out:
2738 return rc;
2739}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002740
2741/* Checks userdata. Attempt to mount the volume if default-
2742 * encrypted.
2743 * On success trigger next init phase and return 0.
2744 * Currently do not handle failure - see TODO below.
2745 */
2746int cryptfs_mount_default_encrypted(void)
2747{
Paul Lawrence84274cc2016-04-15 15:41:33 -07002748 int crypt_type = cryptfs_get_password_type();
2749 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2750 SLOGE("Bad crypt type - error");
2751 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2752 SLOGD("Password is not default - "
2753 "starting min framework to prompt");
2754 property_set("vold.decrypt", "trigger_restart_min_framework");
2755 return 0;
2756 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2757 SLOGD("Password is default - restarting filesystem");
2758 cryptfs_restart_internal(0);
2759 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002760 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002761 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002762 }
2763
Paul Lawrence6bfed202014-07-28 12:47:22 -07002764 /** Corrupt. Allow us to boot into framework, which will detect bad
2765 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002766 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002767 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002768 return 0;
2769}
2770
2771/* Returns type of the password, default, pattern, pin or password.
2772 */
2773int cryptfs_get_password_type(void)
2774{
Paul Crowley38132a12016-02-09 09:50:32 +00002775 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002776 SLOGE("cryptfs_get_password_type not valid for file encryption");
2777 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002778 }
2779
Paul Lawrencef4faa572014-01-29 13:31:03 -08002780 struct crypt_mnt_ftr crypt_ftr;
2781
2782 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2783 SLOGE("Error getting crypt footer and key\n");
2784 return -1;
2785 }
2786
Paul Lawrence6bfed202014-07-28 12:47:22 -07002787 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2788 return -1;
2789 }
2790
Paul Lawrencef4faa572014-01-29 13:31:03 -08002791 return crypt_ftr.crypt_type;
2792}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002793
Paul Lawrence05335c32015-03-05 09:46:23 -08002794const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002795{
Paul Crowley38132a12016-02-09 09:50:32 +00002796 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002797 SLOGE("cryptfs_get_password not valid for file encryption");
2798 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002799 }
2800
Paul Lawrence399317e2014-03-10 13:20:50 -07002801 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002802 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002803 if (now.tv_sec < password_expiry_time) {
2804 return password;
2805 } else {
2806 cryptfs_clear_password();
2807 return 0;
2808 }
2809}
2810
2811void cryptfs_clear_password()
2812{
2813 if (password) {
2814 size_t len = strlen(password);
2815 memset(password, 0, len);
2816 free(password);
2817 password = 0;
2818 password_expiry_time = 0;
2819 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002820}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002821
Paul Lawrence0c247462015-10-29 10:30:57 -07002822int cryptfs_isConvertibleToFBE()
2823{
Paul Crowleye2ee1522017-09-26 14:05:26 -07002824 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Paul Lawrence0c247462015-10-29 10:30:57 -07002825 return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
2826}