blob: 62eb9a776dcba47737ea2289d8e530c0ce294b53 [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
Greg Kaiser57f9af62018-02-16 13:13:58 -0800285uint32_t cryptfs_get_keysize() {
286 return DEFAULT_KEY_LEN_BYTES;
287}
288
289const char *cryptfs_get_crypto_name() {
290 return "aes-cbc-essiv:sha256";
291}
292
Ken Sumrall3ed82362011-01-28 23:31:16 -0800293static unsigned int get_fs_size(char *dev)
294{
295 int fd, block_size;
296 struct ext4_super_block sb;
297 off64_t len;
298
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700299 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800300 SLOGE("Cannot open device to get filesystem size ");
301 return 0;
302 }
303
304 if (lseek64(fd, 1024, SEEK_SET) < 0) {
305 SLOGE("Cannot seek to superblock");
306 return 0;
307 }
308
309 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
310 SLOGE("Cannot read superblock");
311 return 0;
312 }
313
314 close(fd);
315
Daniel Rosenberge82df162014-08-15 22:19:23 +0000316 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
317 SLOGE("Not a valid ext4 superblock");
318 return 0;
319 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800320 block_size = 1024 << sb.s_log_block_size;
321 /* compute length in bytes */
322 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
323
324 /* return length in sectors */
325 return (unsigned int) (len / 512);
326}
327
Ken Sumrall160b4d62013-04-22 12:15:39 -0700328static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
329{
330 static int cached_data = 0;
331 static off64_t cached_off = 0;
332 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
333 int fd;
334 char key_loc[PROPERTY_VALUE_MAX];
335 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700336 int rc = -1;
337
338 if (!cached_data) {
Paul Crowleye2ee1522017-09-26 14:05:26 -0700339 fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700340
341 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700342 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700343 SLOGE("Cannot open real block device %s\n", real_blkdev);
344 return -1;
345 }
346
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900347 unsigned long nr_sec = 0;
348 get_blkdev_size(fd, &nr_sec);
349 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700350 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
351 * encryption info footer and key, and plenty of bytes to spare for future
352 * growth.
353 */
354 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
355 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
356 cached_data = 1;
357 } else {
358 SLOGE("Cannot get size of block device %s\n", real_blkdev);
359 }
360 close(fd);
361 } else {
362 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
363 cached_off = 0;
364 cached_data = 1;
365 }
366 }
367
368 if (cached_data) {
369 if (metadata_fname) {
370 *metadata_fname = cached_metadata_fname;
371 }
372 if (off) {
373 *off = cached_off;
374 }
375 rc = 0;
376 }
377
378 return rc;
379}
380
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800381/* Set sha256 checksum in structure */
382static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr)
383{
384 SHA256_CTX c;
385 SHA256_Init(&c);
386 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
387 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
388 SHA256_Final(crypt_ftr->sha256, &c);
389}
390
Ken Sumralle8744072011-01-18 22:01:55 -0800391/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800392 * update the failed mount count but not change the key.
393 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700394static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800395{
396 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800397 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700398 /* starting_off is set to the SEEK_SET offset
399 * where the crypto structure starts
400 */
401 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800402 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700403 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700404 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800405
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800406 set_ftr_sha(crypt_ftr);
407
Ken Sumrall160b4d62013-04-22 12:15:39 -0700408 if (get_crypt_ftr_info(&fname, &starting_off)) {
409 SLOGE("Unable to get crypt_ftr_info\n");
410 return -1;
411 }
412 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700413 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700414 return -1;
415 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700416 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700417 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700418 return -1;
419 }
420
421 /* Seek to the start of the crypt footer */
422 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
423 SLOGE("Cannot seek to real block device footer\n");
424 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800425 }
426
427 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
428 SLOGE("Cannot write real block device footer\n");
429 goto errout;
430 }
431
Ken Sumrall3be890f2011-09-14 16:53:46 -0700432 fstat(fd, &statbuf);
433 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700434 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700435 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800436 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800437 goto errout;
438 }
439 }
440
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800441 /* Success! */
442 rc = 0;
443
444errout:
445 close(fd);
446 return rc;
447
448}
449
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800450static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr)
451{
452 struct crypt_mnt_ftr copy;
453 memcpy(&copy, crypt_ftr, sizeof(copy));
454 set_ftr_sha(&copy);
455 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
456}
457
Ken Sumrall160b4d62013-04-22 12:15:39 -0700458static inline int unix_read(int fd, void* buff, int len)
459{
460 return TEMP_FAILURE_RETRY(read(fd, buff, len));
461}
462
463static inline int unix_write(int fd, const void* buff, int len)
464{
465 return TEMP_FAILURE_RETRY(write(fd, buff, len));
466}
467
468static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
469{
470 memset(pdata, 0, len);
471 pdata->persist_magic = PERSIST_DATA_MAGIC;
472 pdata->persist_valid_entries = 0;
473}
474
475/* A routine to update the passed in crypt_ftr to the lastest version.
476 * fd is open read/write on the device that holds the crypto footer and persistent
477 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
478 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
479 */
480static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
481{
Kenny Root7434b312013-06-14 11:29:53 -0700482 int orig_major = crypt_ftr->major_version;
483 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700484
Kenny Root7434b312013-06-14 11:29:53 -0700485 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
486 struct crypt_persist_data *pdata;
487 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700488
Kenny Rootc4c70f12013-06-14 12:11:38 -0700489 SLOGW("upgrading crypto footer to 1.1");
490
Wei Wang4375f1b2017-02-24 17:43:01 -0800491 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700492 if (pdata == NULL) {
493 SLOGE("Cannot allocate persisent data\n");
494 return;
495 }
496 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
497
498 /* Need to initialize the persistent data area */
499 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
500 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100501 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700502 return;
503 }
504 /* Write all zeros to the first copy, making it invalid */
505 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
506
507 /* Write a valid but empty structure to the second copy */
508 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
509 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
510
511 /* Update the footer */
512 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
513 crypt_ftr->persist_data_offset[0] = pdata_offset;
514 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
515 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100516 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700517 }
518
Paul Lawrencef4faa572014-01-29 13:31:03 -0800519 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700520 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800521 /* But keep the old kdf_type.
522 * It will get updated later to KDF_SCRYPT after the password has been verified.
523 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700524 crypt_ftr->kdf_type = KDF_PBKDF2;
525 get_device_scrypt_params(crypt_ftr);
526 crypt_ftr->minor_version = 2;
527 }
528
Paul Lawrencef4faa572014-01-29 13:31:03 -0800529 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
530 SLOGW("upgrading crypto footer to 1.3");
531 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
532 crypt_ftr->minor_version = 3;
533 }
534
Kenny Root7434b312013-06-14 11:29:53 -0700535 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
536 if (lseek64(fd, offset, SEEK_SET) == -1) {
537 SLOGE("Cannot seek to crypt footer\n");
538 return;
539 }
540 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700541 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700542}
543
544
545static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800546{
547 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800548 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700549 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800550 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700551 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700552 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800553
Ken Sumrall160b4d62013-04-22 12:15:39 -0700554 if (get_crypt_ftr_info(&fname, &starting_off)) {
555 SLOGE("Unable to get crypt_ftr_info\n");
556 return -1;
557 }
558 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700559 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700560 return -1;
561 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700562 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700563 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700564 return -1;
565 }
566
567 /* Make sure it's 16 Kbytes in length */
568 fstat(fd, &statbuf);
569 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
570 SLOGE("footer file %s is not the expected size!\n", fname);
571 goto errout;
572 }
573
574 /* Seek to the start of the crypt footer */
575 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
576 SLOGE("Cannot seek to real block device footer\n");
577 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800578 }
579
580 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
581 SLOGE("Cannot read real block device footer\n");
582 goto errout;
583 }
584
585 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700586 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800587 goto errout;
588 }
589
Kenny Rootc96a5f82013-06-14 12:08:28 -0700590 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
591 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
592 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800593 goto errout;
594 }
595
Greg Kaiser59ad0182018-02-16 13:01:36 -0800596 // We risk buffer overflows with oversized keys, so we just reject them.
597 // 0-sized keys are problematic (essentially by-passing encryption), and
598 // AES-CBC key wrapping only works for multiples of 16 bytes.
599 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
600 (crypt_ftr->keysize > MAX_KEY_LEN)) {
601 SLOGE("Invalid keysize (%u) for block device %s; Must be non-zero, "
602 "divisible by 16, and <= %d\n", crypt_ftr->keysize, fname,
603 MAX_KEY_LEN);
604 goto errout;
605 }
606
Kenny Rootc96a5f82013-06-14 12:08:28 -0700607 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
608 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
609 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800610 }
611
Ken Sumrall160b4d62013-04-22 12:15:39 -0700612 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
613 * copy on disk before returning.
614 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700615 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700616 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800617 }
618
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800619 /* Success! */
620 rc = 0;
621
622errout:
623 close(fd);
624 return rc;
625}
626
Ken Sumrall160b4d62013-04-22 12:15:39 -0700627static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
628{
629 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
630 crypt_ftr->persist_data_offset[1]) {
631 SLOGE("Crypt_ftr persist data regions overlap");
632 return -1;
633 }
634
635 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
636 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
637 return -1;
638 }
639
640 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
641 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
642 CRYPT_FOOTER_OFFSET) {
643 SLOGE("Persistent data extends past crypto footer");
644 return -1;
645 }
646
647 return 0;
648}
649
650static int load_persistent_data(void)
651{
652 struct crypt_mnt_ftr crypt_ftr;
653 struct crypt_persist_data *pdata = NULL;
654 char encrypted_state[PROPERTY_VALUE_MAX];
655 char *fname;
656 int found = 0;
657 int fd;
658 int ret;
659 int i;
660
661 if (persist_data) {
662 /* Nothing to do, we've already loaded or initialized it */
663 return 0;
664 }
665
666
667 /* If not encrypted, just allocate an empty table and initialize it */
668 property_get("ro.crypto.state", encrypted_state, "");
669 if (strcmp(encrypted_state, "encrypted") ) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800670 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700671 if (pdata) {
672 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
673 persist_data = pdata;
674 return 0;
675 }
676 return -1;
677 }
678
679 if(get_crypt_ftr_and_key(&crypt_ftr)) {
680 return -1;
681 }
682
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700683 if ((crypt_ftr.major_version < 1)
684 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700685 SLOGE("Crypt_ftr version doesn't support persistent data");
686 return -1;
687 }
688
689 if (get_crypt_ftr_info(&fname, NULL)) {
690 return -1;
691 }
692
693 ret = validate_persistent_data_storage(&crypt_ftr);
694 if (ret) {
695 return -1;
696 }
697
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700698 fd = open(fname, O_RDONLY|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700699 if (fd < 0) {
700 SLOGE("Cannot open %s metadata file", fname);
701 return -1;
702 }
703
Wei Wang4375f1b2017-02-24 17:43:01 -0800704 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800705 if (pdata == NULL) {
706 SLOGE("Cannot allocate memory for persistent data");
707 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700708 }
709
710 for (i = 0; i < 2; i++) {
711 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
712 SLOGE("Cannot seek to read persistent data on %s", fname);
713 goto err2;
714 }
715 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
716 SLOGE("Error reading persistent data on iteration %d", i);
717 goto err2;
718 }
719 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
720 found = 1;
721 break;
722 }
723 }
724
725 if (!found) {
726 SLOGI("Could not find valid persistent data, creating");
727 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
728 }
729
730 /* Success */
731 persist_data = pdata;
732 close(fd);
733 return 0;
734
735err2:
736 free(pdata);
737
738err:
739 close(fd);
740 return -1;
741}
742
743static int save_persistent_data(void)
744{
745 struct crypt_mnt_ftr crypt_ftr;
746 struct crypt_persist_data *pdata;
747 char *fname;
748 off64_t write_offset;
749 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700750 int fd;
751 int ret;
752
753 if (persist_data == NULL) {
754 SLOGE("No persistent data to save");
755 return -1;
756 }
757
758 if(get_crypt_ftr_and_key(&crypt_ftr)) {
759 return -1;
760 }
761
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700762 if ((crypt_ftr.major_version < 1)
763 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700764 SLOGE("Crypt_ftr version doesn't support persistent data");
765 return -1;
766 }
767
768 ret = validate_persistent_data_storage(&crypt_ftr);
769 if (ret) {
770 return -1;
771 }
772
773 if (get_crypt_ftr_info(&fname, NULL)) {
774 return -1;
775 }
776
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700777 fd = open(fname, O_RDWR|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700778 if (fd < 0) {
779 SLOGE("Cannot open %s metadata file", fname);
780 return -1;
781 }
782
Wei Wang4375f1b2017-02-24 17:43:01 -0800783 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700784 if (pdata == NULL) {
785 SLOGE("Cannot allocate persistant data");
786 goto err;
787 }
788
789 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
790 SLOGE("Cannot seek to read persistent data on %s", fname);
791 goto err2;
792 }
793
794 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
795 SLOGE("Error reading persistent data before save");
796 goto err2;
797 }
798
799 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
800 /* The first copy is the curent valid copy, so write to
801 * the second copy and erase this one */
802 write_offset = crypt_ftr.persist_data_offset[1];
803 erase_offset = crypt_ftr.persist_data_offset[0];
804 } else {
805 /* The second copy must be the valid copy, so write to
806 * the first copy, and erase the second */
807 write_offset = crypt_ftr.persist_data_offset[0];
808 erase_offset = crypt_ftr.persist_data_offset[1];
809 }
810
811 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100812 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700813 SLOGE("Cannot seek to write persistent data");
814 goto err2;
815 }
816 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
817 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100818 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700819 SLOGE("Cannot seek to erase previous persistent data");
820 goto err2;
821 }
822 fsync(fd);
823 memset(pdata, 0, crypt_ftr.persist_data_size);
824 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
825 (int) crypt_ftr.persist_data_size) {
826 SLOGE("Cannot write to erase previous persistent data");
827 goto err2;
828 }
829 fsync(fd);
830 } else {
831 SLOGE("Cannot write to save persistent data");
832 goto err2;
833 }
834
835 /* Success */
836 free(pdata);
837 close(fd);
838 return 0;
839
840err2:
841 free(pdata);
842err:
843 close(fd);
844 return -1;
845}
846
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800847/* Convert a binary key of specified length into an ascii hex string equivalent,
848 * without the leading 0x and with null termination
849 */
Jeff Sharkey9c484982015-03-31 10:35:33 -0700850static void convert_key_to_hex_ascii(const unsigned char *master_key,
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700851 unsigned int keysize, char *master_key_ascii) {
852 unsigned int i, a;
853 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800854
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700855 for (i=0, a=0; i<keysize; i++, a+=2) {
856 /* For each byte, write out two ascii hex digits */
857 nibble = (master_key[i] >> 4) & 0xf;
858 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800859
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700860 nibble = master_key[i] & 0xf;
861 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
862 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800863
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700864 /* Add the null termination */
865 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800866
867}
868
Jeff Sharkey9c484982015-03-31 10:35:33 -0700869static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
870 const unsigned char *master_key, const char *real_blk_name,
871 const char *name, int fd, const char *extra_params) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800872 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800873 struct dm_ioctl *io;
874 struct dm_target_spec *tgt;
875 char *crypt_params;
Greg Kaiser59ad0182018-02-16 13:01:36 -0800876 // We need two ASCII characters to represent each byte, and need space for
877 // the '\0' terminator.
878 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
George Burgess IV605d7ae2016-02-29 13:39:17 -0800879 size_t buff_offset;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800880 int i;
881
882 io = (struct dm_ioctl *) buffer;
883
884 /* Load the mapping table for this device */
885 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
886
887 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
888 io->target_count = 1;
889 tgt->status = 0;
890 tgt->sector_start = 0;
891 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -0700892 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800893
894 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
895 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800896
897 buff_offset = crypt_params - buffer;
Paul Crowley5afbc622017-11-27 09:42:17 -0800898 SLOGI("Extra parameters for dm_crypt: %s\n", extra_params);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800899 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
900 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name,
901 extra_params);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800902 crypt_params += strlen(crypt_params) + 1;
903 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
904 tgt->next = crypt_params - buffer;
905
906 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
907 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
908 break;
909 }
910 usleep(500000);
911 }
912
913 if (i == TABLE_LOAD_RETRIES) {
914 /* We failed to load the table, return an error */
915 return -1;
916 } else {
917 return i + 1;
918 }
919}
920
921
922static int get_dm_crypt_version(int fd, const char *name, int *version)
923{
924 char buffer[DM_CRYPT_BUF_SIZE];
925 struct dm_ioctl *io;
926 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800927
928 io = (struct dm_ioctl *) buffer;
929
930 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
931
932 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
933 return -1;
934 }
935
936 /* Iterate over the returned versions, looking for name of "crypt".
937 * When found, get and return the version.
938 */
939 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
940 while (v->next) {
941 if (! strcmp(v->name, "crypt")) {
942 /* We found the crypt driver, return the version, and get out */
943 version[0] = v->version[0];
944 version[1] = v->version[1];
945 version[2] = v->version[2];
946 return 0;
947 }
948 v = (struct dm_target_versions *)(((char *)v) + v->next);
949 }
950
951 return -1;
952}
953
Paul Crowley5afbc622017-11-27 09:42:17 -0800954static std::string extra_params_as_string(const std::vector<std::string>& extra_params_vec) {
955 if (extra_params_vec.empty()) return "";
956 std::string extra_params = std::to_string(extra_params_vec.size());
957 for (const auto& p : extra_params_vec) {
958 extra_params.append(" ");
959 extra_params.append(p);
960 }
961 return extra_params;
962}
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800963
Paul Crowley5afbc622017-11-27 09:42:17 -0800964static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
965 const char* real_blk_name, char* crypto_blk_name, const char* name,
966 uint32_t flags) {
967 char buffer[DM_CRYPT_BUF_SIZE];
968 struct dm_ioctl* io;
969 unsigned int minor;
970 int fd = 0;
971 int err;
972 int retval = -1;
973 int version[3];
974 int load_count;
975 std::vector<std::string> extra_params_vec;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800976
Paul Crowley5afbc622017-11-27 09:42:17 -0800977 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
978 SLOGE("Cannot open device-mapper\n");
979 goto errout;
980 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800981
Paul Crowley5afbc622017-11-27 09:42:17 -0800982 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800983
Paul Crowley5afbc622017-11-27 09:42:17 -0800984 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
985 err = ioctl(fd, DM_DEV_CREATE, io);
986 if (err) {
987 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
988 goto errout;
989 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800990
Paul Crowley5afbc622017-11-27 09:42:17 -0800991 /* Get the device status, in particular, the name of it's device file */
992 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
993 if (ioctl(fd, DM_DEV_STATUS, io)) {
994 SLOGE("Cannot retrieve dm-crypt device status\n");
995 goto errout;
996 }
997 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
998 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
Ken Sumralle919efe2012-09-29 17:07:41 -0700999
Paul Crowley5afbc622017-11-27 09:42:17 -08001000 if (!get_dm_crypt_version(fd, name, version)) {
1001 /* Support for allow_discards was added in version 1.11.0 */
1002 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
1003 extra_params_vec.emplace_back("allow_discards");
1004 }
1005 }
1006 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
1007 extra_params_vec.emplace_back("allow_encrypt_override");
1008 }
1009 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1010 extra_params_as_string(extra_params_vec).c_str());
1011 if (load_count < 0) {
1012 SLOGE("Cannot load dm-crypt mapping table.\n");
1013 goto errout;
1014 } else if (load_count > 1) {
1015 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1016 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001017
Paul Crowley5afbc622017-11-27 09:42:17 -08001018 /* Resume this device to activate it */
1019 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001020
Paul Crowley5afbc622017-11-27 09:42:17 -08001021 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1022 SLOGE("Cannot resume the dm-crypt device\n");
1023 goto errout;
1024 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001025
Paul Crowley5afbc622017-11-27 09:42:17 -08001026 /* We made it here with no errors. Woot! */
1027 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001028
1029errout:
1030 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1031
1032 return retval;
1033}
1034
Wei Wang4375f1b2017-02-24 17:43:01 -08001035static int delete_crypto_blk_dev(const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001036{
1037 int fd;
1038 char buffer[DM_CRYPT_BUF_SIZE];
1039 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001040 int retval = -1;
1041
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001042 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001043 SLOGE("Cannot open device-mapper\n");
1044 goto errout;
1045 }
1046
1047 io = (struct dm_ioctl *) buffer;
1048
1049 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1050 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1051 SLOGE("Cannot remove dm-crypt device\n");
1052 goto errout;
1053 }
1054
1055 /* We made it here with no errors. Woot! */
1056 retval = 0;
1057
1058errout:
1059 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1060
1061 return retval;
1062
1063}
1064
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001065static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001066 unsigned char *ikey, void *params UNUSED)
1067{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001068 SLOGI("Using pbkdf2 for cryptfs KDF");
1069
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001070 /* Turn the password into a key and IV that can decrypt the master key */
Adam Langleybf0d9722015-11-04 14:51:39 -08001071 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001072 HASH_COUNT, INTERMEDIATE_BUF_SIZE,
Adam Langleybf0d9722015-11-04 14:51:39 -08001073 ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001074}
1075
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001076static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001077 unsigned char *ikey, void *params)
1078{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001079 SLOGI("Using scrypt for cryptfs KDF");
1080
Kenny Rootc4c70f12013-06-14 12:11:38 -07001081 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1082
1083 int N = 1 << ftr->N_factor;
1084 int r = 1 << ftr->r_factor;
1085 int p = 1 << ftr->p_factor;
1086
1087 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001088 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1089 salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001090 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001091
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001092 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001093}
1094
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001095static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1096 unsigned char *ikey, void *params)
1097{
1098 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1099
1100 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001101 size_t signature_size;
1102 unsigned char* signature;
1103 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1104
1105 int N = 1 << ftr->N_factor;
1106 int r = 1 << ftr->r_factor;
1107 int p = 1 << ftr->p_factor;
1108
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001109 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1110 salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001111 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001112
1113 if (rc) {
1114 SLOGE("scrypt failed");
1115 return -1;
1116 }
1117
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001118 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE,
Shawn Willdene17a9c42014-09-08 13:04:08 -06001119 &signature, &signature_size)) {
1120 SLOGE("Signing failed");
1121 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001122 }
1123
1124 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001125 N, r, p, ikey, INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001126 free(signature);
1127
1128 if (rc) {
1129 SLOGE("scrypt failed");
1130 return -1;
1131 }
1132
1133 return 0;
1134}
1135
1136static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1137 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001138 unsigned char *encrypted_master_key,
1139 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001140{
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001141 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = { 0 };
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001142 EVP_CIPHER_CTX e_ctx;
1143 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001144 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001145
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001146 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001147 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001148
1149 switch (crypt_ftr->kdf_type) {
1150 case KDF_SCRYPT_KEYMASTER:
1151 if (keymaster_create_key(crypt_ftr)) {
1152 SLOGE("keymaster_create_key failed");
1153 return -1;
1154 }
1155
1156 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1157 SLOGE("scrypt failed");
1158 return -1;
1159 }
1160 break;
1161
1162 case KDF_SCRYPT:
1163 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1164 SLOGE("scrypt failed");
1165 return -1;
1166 }
1167 break;
1168
1169 default:
1170 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001171 return -1;
1172 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001173
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001174 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001175 EVP_CIPHER_CTX_init(&e_ctx);
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001176 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1177 ikey+INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001178 SLOGE("EVP_EncryptInit failed\n");
1179 return -1;
1180 }
1181 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001182
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001183 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001184 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Greg Kaiser59ad0182018-02-16 13:01:36 -08001185 decrypted_master_key, crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001186 SLOGE("EVP_EncryptUpdate failed\n");
1187 return -1;
1188 }
Adam Langley889c4f12014-09-03 14:23:13 -07001189 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001190 SLOGE("EVP_EncryptFinal failed\n");
1191 return -1;
1192 }
1193
Greg Kaiser59ad0182018-02-16 13:01:36 -08001194 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001195 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1196 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001197 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001198
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001199 /* Store the scrypt of the intermediate key, so we can validate if it's a
1200 password error or mount error when things go wrong.
1201 Note there's no need to check for errors, since if this is incorrect, we
1202 simply won't wipe userdata, which is the correct default behavior
1203 */
1204 int N = 1 << crypt_ftr->N_factor;
1205 int r = 1 << crypt_ftr->r_factor;
1206 int p = 1 << crypt_ftr->p_factor;
1207
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001208 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001209 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1210 crypt_ftr->scrypted_intermediate_key,
1211 sizeof(crypt_ftr->scrypted_intermediate_key));
1212
1213 if (rc) {
1214 SLOGE("encrypt_master_key: crypto_scrypt failed");
1215 }
1216
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001217 EVP_CIPHER_CTX_cleanup(&e_ctx);
1218
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001219 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001220}
1221
Paul Lawrence731a7a22015-04-28 22:14:15 +00001222static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Greg Kaiser59ad0182018-02-16 13:01:36 -08001223 const unsigned char *encrypted_master_key,
1224 size_t keysize,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001225 unsigned char *decrypted_master_key,
1226 kdf_func kdf, void *kdf_params,
1227 unsigned char** intermediate_key,
1228 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001229{
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001230 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = { 0 };
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001231 EVP_CIPHER_CTX d_ctx;
1232 int decrypted_len, final_len;
1233
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001234 /* Turn the password into an intermediate key and IV that can decrypt the
1235 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001236 if (kdf(passwd, salt, ikey, kdf_params)) {
1237 SLOGE("kdf failed");
1238 return -1;
1239 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001240
1241 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001242 EVP_CIPHER_CTX_init(&d_ctx);
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001243 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001244 return -1;
1245 }
1246 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1247 /* Decrypt the master key */
1248 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
Greg Kaiser59ad0182018-02-16 13:01:36 -08001249 encrypted_master_key, keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001250 return -1;
1251 }
Adam Langley889c4f12014-09-03 14:23:13 -07001252 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001253 return -1;
1254 }
1255
Greg Kaiser59ad0182018-02-16 13:01:36 -08001256 if (decrypted_len + final_len != static_cast<int>(keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001257 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001258 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001259
1260 /* Copy intermediate key if needed by params */
1261 if (intermediate_key && intermediate_key_size) {
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001262 *intermediate_key = (unsigned char*) malloc(INTERMEDIATE_KEY_LEN_BYTES);
Greg Kaisere8167af2016-04-20 10:50:15 -07001263 if (*intermediate_key) {
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001264 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1265 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001266 }
1267 }
1268
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001269 EVP_CIPHER_CTX_cleanup(&d_ctx);
1270
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001271 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001272}
1273
Kenny Rootc4c70f12013-06-14 12:11:38 -07001274static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001275{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001276 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001277 *kdf = scrypt_keymaster;
1278 *kdf_params = ftr;
1279 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001280 *kdf = scrypt;
1281 *kdf_params = ftr;
1282 } else {
1283 *kdf = pbkdf2;
1284 *kdf_params = NULL;
1285 }
1286}
1287
Paul Lawrence731a7a22015-04-28 22:14:15 +00001288static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001289 struct crypt_mnt_ftr *crypt_ftr,
1290 unsigned char** intermediate_key,
1291 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001292{
1293 kdf_func kdf;
1294 void *kdf_params;
1295 int ret;
1296
1297 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001298 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
Greg Kaiser59ad0182018-02-16 13:01:36 -08001299 crypt_ftr->keysize,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001300 decrypted_master_key, kdf, kdf_params,
1301 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001302 if (ret != 0) {
1303 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001304 }
1305
1306 return ret;
1307}
1308
Wei Wang4375f1b2017-02-24 17:43:01 -08001309static int create_encrypted_random_key(const char *passwd, unsigned char *master_key, unsigned char *salt,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001310 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001311 int fd;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001312 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001313
1314 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001315 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001316 read(fd, key_buf, sizeof(key_buf));
1317 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001318 close(fd);
1319
1320 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001321 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001322}
1323
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001324int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001325{
Greg Hackmann955653e2014-09-24 14:55:20 -07001326 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001327#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001328
1329 /* Now umount the tmpfs filesystem */
1330 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001331 if (umount(mountpoint) == 0) {
1332 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001333 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001334
1335 if (errno == EINVAL) {
1336 /* EINVAL is returned if the directory is not a mountpoint,
1337 * i.e. there is no filesystem mounted there. So just get out.
1338 */
1339 break;
1340 }
1341
1342 err = errno;
1343
1344 /* If allowed, be increasingly aggressive before the last two retries */
1345 if (kill) {
1346 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1347 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001348 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001349 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1350 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001351 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001352 }
1353 }
1354
1355 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001356 }
1357
1358 if (i < WAIT_UNMOUNT_COUNT) {
1359 SLOGD("unmounting %s succeeded\n", mountpoint);
1360 rc = 0;
1361 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001362 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001363 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001364 rc = -1;
1365 }
1366
1367 return rc;
1368}
1369
Wei Wang42e38102017-06-07 10:46:12 -07001370static void prep_data_fs(void)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001371{
Jeff Sharkey47695b22016-02-01 17:02:29 -07001372 // NOTE: post_fs_data results in init calling back around to vold, so all
1373 // callers to this method must be async
1374
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001375 /* Do the prep of the /data filesystem */
1376 property_set("vold.post_fs_data_done", "0");
1377 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001378 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001379
Ken Sumrallc5872692013-05-14 15:26:31 -07001380 /* Wait a max of 50 seconds, hopefully it takes much less */
Wei Wang42e38102017-06-07 10:46:12 -07001381 while (!android::base::WaitForProperty("vold.post_fs_data_done",
Wei Wang4375f1b2017-02-24 17:43:01 -08001382 "1",
Wei Wang42e38102017-06-07 10:46:12 -07001383 std::chrono::seconds(15))) {
1384 /* We timed out to prep /data in time. Continue wait. */
1385 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001386 }
Wei Wang42e38102017-06-07 10:46:12 -07001387 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001388}
1389
Paul Lawrence74f29f12014-08-28 15:54:10 -07001390static void cryptfs_set_corrupt()
1391{
1392 // Mark the footer as bad
1393 struct crypt_mnt_ftr crypt_ftr;
1394 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1395 SLOGE("Failed to get crypto footer - panic");
1396 return;
1397 }
1398
1399 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1400 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1401 SLOGE("Failed to set crypto footer - panic");
1402 return;
1403 }
1404}
1405
1406static void cryptfs_trigger_restart_min_framework()
1407{
1408 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1409 SLOGE("Failed to mount tmpfs on data - panic");
1410 return;
1411 }
1412
1413 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1414 SLOGE("Failed to trigger post fs data - panic");
1415 return;
1416 }
1417
1418 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1419 SLOGE("Failed to trigger restart min framework - panic");
1420 return;
1421 }
1422}
1423
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001424/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001425static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001426{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001427 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001428 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001429 static int restart_successful = 0;
1430
1431 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001432 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001433 SLOGE("Encrypted filesystem not validated, aborting");
1434 return -1;
1435 }
1436
1437 if (restart_successful) {
1438 SLOGE("System already restarted with encrypted disk, aborting");
1439 return -1;
1440 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001441
Paul Lawrencef4faa572014-01-29 13:31:03 -08001442 if (restart_main) {
1443 /* Here is where we shut down the framework. The init scripts
1444 * start all services in one of three classes: core, main or late_start.
1445 * On boot, we start core and main. Now, we stop main, but not core,
1446 * as core includes vold and a few other really important things that
1447 * we need to keep running. Once main has stopped, we should be able
1448 * to umount the tmpfs /data, then mount the encrypted /data.
1449 * We then restart the class main, and also the class late_start.
1450 * At the moment, I've only put a few things in late_start that I know
1451 * are not needed to bring up the framework, and that also cause problems
1452 * with unmounting the tmpfs /data, but I hope to add add more services
1453 * to the late_start class as we optimize this to decrease the delay
1454 * till the user is asked for the password to the filesystem.
1455 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001456
Paul Lawrencef4faa572014-01-29 13:31:03 -08001457 /* The init files are setup to stop the class main when vold.decrypt is
1458 * set to trigger_reset_main.
1459 */
1460 property_set("vold.decrypt", "trigger_reset_main");
1461 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001462
Paul Lawrencef4faa572014-01-29 13:31:03 -08001463 /* Ugh, shutting down the framework is not synchronous, so until it
1464 * can be fixed, this horrible hack will wait a moment for it all to
1465 * shut down before proceeding. Without it, some devices cannot
1466 * restart the graphics services.
1467 */
1468 sleep(2);
1469 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001470
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001471 /* Now that the framework is shutdown, we should be able to umount()
1472 * the tmpfs filesystem, and mount the real one.
1473 */
1474
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001475 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1476 if (strlen(crypto_blkdev) == 0) {
1477 SLOGE("fs_crypto_blkdev not set\n");
1478 return -1;
1479 }
1480
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001481 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001482 /* If ro.crypto.readonly is set to 1, mount the decrypted
1483 * filesystem readonly. This is used when /data is mounted by
1484 * recovery mode.
1485 */
1486 char ro_prop[PROPERTY_VALUE_MAX];
1487 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001488 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001489 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Doug Zongker6fd57712013-12-17 09:43:23 -08001490 rec->flags |= MS_RDONLY;
1491 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001492
Ken Sumralle5032c42012-04-01 23:58:44 -07001493 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001494 int retries = RETRY_MOUNT_ATTEMPTS;
1495 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001496
1497 /*
1498 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1499 * partitions in the fsck domain.
1500 */
1501 if (setexeccon(secontextFsck())){
1502 SLOGE("Failed to setexeccon");
1503 return -1;
1504 }
Paul Crowleye2ee1522017-09-26 14:05:26 -07001505 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT,
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001506 crypto_blkdev, 0))
1507 != 0) {
1508 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1509 /* TODO: invoke something similar to
1510 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1511 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1512 SLOGI("Failed to mount %s because it is busy - waiting",
1513 crypto_blkdev);
1514 if (--retries) {
1515 sleep(RETRY_MOUNT_DELAY_SECONDS);
1516 } else {
1517 /* Let's hope that a reboot clears away whatever is keeping
1518 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001519 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001520 }
1521 } else {
1522 SLOGE("Failed to mount decrypted data");
1523 cryptfs_set_corrupt();
1524 cryptfs_trigger_restart_min_framework();
1525 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001526 if (setexeccon(NULL)) {
1527 SLOGE("Failed to setexeccon");
1528 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001529 return -1;
1530 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001531 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001532 if (setexeccon(NULL)) {
1533 SLOGE("Failed to setexeccon");
1534 return -1;
1535 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001536
Ken Sumralle5032c42012-04-01 23:58:44 -07001537 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001538 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001539 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001540
1541 /* startup service classes main and late_start */
1542 property_set("vold.decrypt", "trigger_restart_framework");
1543 SLOGD("Just triggered restart_framework\n");
1544
1545 /* Give it a few moments to get started */
1546 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001547 }
1548
Ken Sumrall0cc16632011-01-18 20:32:26 -08001549 if (rc == 0) {
1550 restart_successful = 1;
1551 }
1552
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001553 return rc;
1554}
1555
Paul Lawrencef4faa572014-01-29 13:31:03 -08001556int cryptfs_restart(void)
1557{
Paul Lawrence05335c32015-03-05 09:46:23 -08001558 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001559 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001560 SLOGE("cryptfs_restart not valid for file encryption:");
1561 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001562 }
1563
Paul Lawrencef4faa572014-01-29 13:31:03 -08001564 /* Call internal implementation forcing a restart of main service group */
1565 return cryptfs_restart_internal(1);
1566}
1567
Wei Wang4375f1b2017-02-24 17:43:01 -08001568static int do_crypto_complete(const char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001569{
1570 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001571 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001572 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001573
1574 property_get("ro.crypto.state", encrypted_state, "");
1575 if (strcmp(encrypted_state, "encrypted") ) {
1576 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001577 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001578 }
1579
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001580 // crypto_complete is full disk encrypted status
Paul Crowley38132a12016-02-09 09:50:32 +00001581 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001582 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Paul Lawrence05335c32015-03-05 09:46:23 -08001583 }
1584
Ken Sumrall160b4d62013-04-22 12:15:39 -07001585 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001586 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001587
Ken Sumralle1a45852011-12-14 21:24:27 -08001588 /*
1589 * Only report this error if key_loc is a file and it exists.
1590 * If the device was never encrypted, and /data is not mountable for
1591 * some reason, returning 1 should prevent the UI from presenting the
1592 * a "enter password" screen, or worse, a "press button to wipe the
1593 * device" screen.
1594 */
1595 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1596 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001597 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001598 } else {
1599 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001600 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001601 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001602 }
1603
Paul Lawrence74f29f12014-08-28 15:54:10 -07001604 // Test for possible error flags
1605 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1606 SLOGE("Encryption process is partway completed\n");
1607 return CRYPTO_COMPLETE_PARTIAL;
1608 }
1609
1610 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1611 SLOGE("Encryption process was interrupted but cannot continue\n");
1612 return CRYPTO_COMPLETE_INCONSISTENT;
1613 }
1614
1615 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1616 SLOGE("Encryption is successful but data is corrupt\n");
1617 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001618 }
1619
1620 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001621 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001622}
1623
Paul Lawrencef4faa572014-01-29 13:31:03 -08001624static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
Wei Wang4375f1b2017-02-24 17:43:01 -08001625 const char *passwd, const char *mount_point, const char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001626{
Greg Kaiser59ad0182018-02-16 13:01:36 -08001627 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001628 char crypto_blkdev[MAXPATHLEN];
1629 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001630 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001631 unsigned int orig_failed_decrypt_count;
1632 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001633 int use_keymaster = 0;
1634 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001635 unsigned char* intermediate_key = 0;
1636 size_t intermediate_key_size = 0;
Wei Wang4375f1b2017-02-24 17:43:01 -08001637 int N = 1 << crypt_ftr->N_factor;
1638 int r = 1 << crypt_ftr->r_factor;
1639 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001640
Paul Lawrencef4faa572014-01-29 13:31:03 -08001641 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1642 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001643
Paul Lawrencef4faa572014-01-29 13:31:03 -08001644 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001645 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1646 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001647 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001648 rc = -1;
1649 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001650 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001651 }
1652
Paul Crowleye2ee1522017-09-26 14:05:26 -07001653 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Paul Lawrencef4faa572014-01-29 13:31:03 -08001654
Paul Lawrence74f29f12014-08-28 15:54:10 -07001655 // Create crypto block device - all (non fatal) code paths
1656 // need it
Paul Crowley5afbc622017-11-27 09:42:17 -08001657 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label, 0)) {
1658 SLOGE("Error creating decrypted block device\n");
1659 rc = -1;
1660 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001661 }
1662
Paul Lawrence74f29f12014-08-28 15:54:10 -07001663 /* Work out if the problem is the password or the data */
1664 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1665 scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001666
Paul Lawrence74f29f12014-08-28 15:54:10 -07001667 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1668 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1669 N, r, p, scrypted_intermediate_key,
1670 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001671
Paul Lawrence74f29f12014-08-28 15:54:10 -07001672 // Does the key match the crypto footer?
1673 if (rc == 0 && memcmp(scrypted_intermediate_key,
1674 crypt_ftr->scrypted_intermediate_key,
1675 sizeof(scrypted_intermediate_key)) == 0) {
1676 SLOGI("Password matches");
1677 rc = 0;
1678 } else {
1679 /* Try mounting the file system anyway, just in case the problem's with
1680 * the footer, not the key. */
George Burgess IV605d7ae2016-02-29 13:39:17 -08001681 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt",
1682 mount_point);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001683 mkdir(tmp_mount_point, 0755);
Paul Crowleye2ee1522017-09-26 14:05:26 -07001684 if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001685 SLOGE("Error temp mounting decrypted block device\n");
1686 delete_crypto_blk_dev(label);
1687
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001688 rc = ++crypt_ftr->failed_decrypt_count;
1689 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001690 } else {
1691 /* Success! */
1692 SLOGI("Password did not match but decrypted drive mounted - continue");
1693 umount(tmp_mount_point);
1694 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001695 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001696 }
1697
1698 if (rc == 0) {
1699 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001700 if (orig_failed_decrypt_count != 0) {
1701 put_crypt_ftr_and_key(crypt_ftr);
1702 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001703
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001704 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001705 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001706 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001707
1708 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001709 * the key when we want to change the password on it. */
Greg Kaiser59ad0182018-02-16 13:01:36 -08001710 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001711 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001712 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001713 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001714 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001715
Paul Lawrence74f29f12014-08-28 15:54:10 -07001716 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001717 use_keymaster = keymaster_check_compatibility();
1718 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001719 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001720 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1721 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1722 upgrade = 1;
1723 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001724 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001725 upgrade = 1;
1726 }
1727
1728 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001729 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1730 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001731 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001732 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001733 }
1734 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001735
1736 // Do not fail even if upgrade failed - machine is bootable
1737 // Note that if this code is ever hit, there is a *serious* problem
1738 // since KDFs should never fail. You *must* fix the kdf before
1739 // proceeding!
1740 if (rc) {
1741 SLOGW("Upgrade failed with error %d,"
1742 " but continuing with previous state",
1743 rc);
1744 rc = 0;
1745 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001746 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001747 }
1748
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001749 errout:
1750 if (intermediate_key) {
1751 memset(intermediate_key, 0, intermediate_key_size);
1752 free(intermediate_key);
1753 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001754 return rc;
1755}
1756
Ken Sumrall29d8da82011-05-18 17:20:07 -07001757/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001758 * Called by vold when it's asked to mount an encrypted external
1759 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08001760 * as any metadata is been stored in a separate, small partition. We
1761 * assume it must be using our same crypt type and keysize.
Jeff Sharkey9c484982015-03-31 10:35:33 -07001762 *
1763 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001764 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001765int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
Greg Kaiser57f9af62018-02-16 13:13:58 -08001766 const unsigned char* key, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001767 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001768 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001769 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001770 return -1;
1771 }
1772
1773 unsigned long nr_sec = 0;
1774 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001775 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001776
Ken Sumrall29d8da82011-05-18 17:20:07 -07001777 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001778 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001779 return -1;
1780 }
1781
Jeff Sharkey9c484982015-03-31 10:35:33 -07001782 struct crypt_mnt_ftr ext_crypt_ftr;
1783 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1784 ext_crypt_ftr.fs_size = nr_sec;
Greg Kaiser57f9af62018-02-16 13:13:58 -08001785 ext_crypt_ftr.keysize = cryptfs_get_keysize();
1786 strlcpy((char*) ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001787 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001788
Paul Crowley5afbc622017-11-27 09:42:17 -08001789 return create_crypto_blk_dev(
1790 &ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label,
1791 e4crypt_is_native() ? CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE : 0);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001792}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001793
Jeff Sharkey9c484982015-03-31 10:35:33 -07001794/*
1795 * Called by vold when it's asked to unmount an encrypted external
1796 * storage volume.
1797 */
1798int cryptfs_revert_ext_volume(const char* label) {
1799 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001800}
1801
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001802int cryptfs_crypto_complete(void)
1803{
1804 return do_crypto_complete("/data");
1805}
1806
Paul Lawrencef4faa572014-01-29 13:31:03 -08001807int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1808{
1809 char encrypted_state[PROPERTY_VALUE_MAX];
1810 property_get("ro.crypto.state", encrypted_state, "");
1811 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1812 SLOGE("encrypted fs already validated or not running with encryption,"
1813 " aborting");
1814 return -1;
1815 }
1816
1817 if (get_crypt_ftr_and_key(crypt_ftr)) {
1818 SLOGE("Error getting crypt footer and key");
1819 return -1;
1820 }
1821
1822 return 0;
1823}
1824
Wei Wang4375f1b2017-02-24 17:43:01 -08001825int cryptfs_check_passwd(const char *passwd)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001826{
Paul Lawrence05335c32015-03-05 09:46:23 -08001827 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00001828 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001829 SLOGE("cryptfs_check_passwd not valid for file encryption");
1830 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001831 }
1832
Paul Lawrencef4faa572014-01-29 13:31:03 -08001833 struct crypt_mnt_ftr crypt_ftr;
1834 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001835
Paul Lawrencef4faa572014-01-29 13:31:03 -08001836 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001837 if (rc) {
1838 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001839 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001840 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001841
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001842 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001843 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1844 if (rc) {
1845 SLOGE("Password did not match");
1846 return rc;
1847 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001848
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001849 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1850 // Here we have a default actual password but a real password
1851 // we must test against the scrypted value
1852 // First, we must delete the crypto block device that
1853 // test_mount_encrypted_fs leaves behind as a side effect
1854 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
1855 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
1856 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1857 if (rc) {
1858 SLOGE("Default password did not match on reboot encryption");
1859 return rc;
1860 }
1861
1862 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1863 put_crypt_ftr_and_key(&crypt_ftr);
1864 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1865 if (rc) {
1866 SLOGE("Could not change password on reboot encryption");
1867 return rc;
1868 }
1869 }
1870
1871 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001872 cryptfs_clear_password();
1873 password = strdup(passwd);
1874 struct timespec now;
1875 clock_gettime(CLOCK_BOOTTIME, &now);
1876 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001877 }
1878
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001879 return rc;
1880}
1881
Jeff Sharkey83b559c2017-09-12 16:30:52 -06001882int cryptfs_verify_passwd(const char *passwd)
Ken Sumrall3ad90722011-10-04 20:38:29 -07001883{
1884 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001885 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001886 char encrypted_state[PROPERTY_VALUE_MAX];
1887 int rc;
1888
1889 property_get("ro.crypto.state", encrypted_state, "");
1890 if (strcmp(encrypted_state, "encrypted") ) {
1891 SLOGE("device not encrypted, aborting");
1892 return -2;
1893 }
1894
1895 if (!master_key_saved) {
1896 SLOGE("encrypted fs not yet mounted, aborting");
1897 return -1;
1898 }
1899
1900 if (!saved_mount_point) {
1901 SLOGE("encrypted fs failed to save mount point, aborting");
1902 return -1;
1903 }
1904
Ken Sumrall160b4d62013-04-22 12:15:39 -07001905 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001906 SLOGE("Error getting crypt footer and key\n");
1907 return -1;
1908 }
1909
1910 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1911 /* If the device has no password, then just say the password is valid */
1912 rc = 0;
1913 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001914 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001915 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1916 /* They match, the password is correct */
1917 rc = 0;
1918 } else {
1919 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1920 sleep(1);
1921 rc = 1;
1922 }
1923 }
1924
1925 return rc;
1926}
1927
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001928/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser57f9af62018-02-16 13:13:58 -08001929 * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001930 * Presumably, at a minimum, the caller will update the
1931 * filesystem size and crypto_type_name after calling this function.
1932 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001933static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001934{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001935 off64_t off;
1936
1937 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001938 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001939 ftr->major_version = CURRENT_MAJOR_VERSION;
1940 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001941 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser57f9af62018-02-16 13:13:58 -08001942 ftr->keysize = cryptfs_get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07001943
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001944 switch (keymaster_check_compatibility()) {
1945 case 1:
1946 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1947 break;
1948
1949 case 0:
1950 ftr->kdf_type = KDF_SCRYPT;
1951 break;
1952
1953 default:
1954 SLOGE("keymaster_check_compatibility failed");
1955 return -1;
1956 }
1957
Kenny Rootc4c70f12013-06-14 12:11:38 -07001958 get_device_scrypt_params(ftr);
1959
Ken Sumrall160b4d62013-04-22 12:15:39 -07001960 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1961 if (get_crypt_ftr_info(NULL, &off) == 0) {
1962 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1963 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1964 ftr->persist_data_size;
1965 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001966
1967 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001968}
1969
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001970#define FRAMEWORK_BOOT_WAIT 60
1971
Paul Lawrence87999172014-02-20 12:21:31 -08001972static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
1973{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001974 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08001975 if (fd == -1) {
1976 SLOGE("Error opening file %s", filename);
1977 return -1;
1978 }
1979
1980 char block[CRYPT_INPLACE_BUFSIZE];
1981 memset(block, 0, sizeof(block));
1982 if (unix_read(fd, block, sizeof(block)) < 0) {
1983 SLOGE("Error reading file %s", filename);
1984 close(fd);
1985 return -1;
1986 }
1987
1988 close(fd);
1989
1990 SHA256_CTX c;
1991 SHA256_Init(&c);
1992 SHA256_Update(&c, block, sizeof(block));
1993 SHA256_Final(buf, &c);
1994
1995 return 0;
1996}
1997
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001998static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
1999 char* real_blkdev, int previously_encrypted_upto) {
Paul Lawrence87999172014-02-20 12:21:31 -08002000 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002001 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002002
Paul Lawrence87999172014-02-20 12:21:31 -08002003 /* The size of the userdata partition, and add in the vold volumes below */
2004 tot_encryption_size = crypt_ftr->fs_size;
2005
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002006 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002007 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002008
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002009 if (rc == ENABLE_INPLACE_ERR_DEV) {
2010 /* Hack for b/17898962 */
2011 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2012 cryptfs_reboot(RebootType::reboot);
2013 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002014
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002015 if (!rc) {
2016 crypt_ftr->encrypted_upto = cur_encryption_done;
2017 }
Paul Lawrence87999172014-02-20 12:21:31 -08002018
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002019 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2020 /* The inplace routine never actually sets the progress to 100% due
2021 * to the round down nature of integer division, so set it here */
2022 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002023 }
2024
2025 return rc;
2026}
2027
Paul Crowleyb64933a2017-10-31 08:25:55 -07002028static int vold_unmountAll(void) {
2029 VolumeManager* vm = VolumeManager::Instance();
2030 return vm->unmountAll();
2031}
2032
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002033int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Lawrence87999172014-02-20 12:21:31 -08002034 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Greg Kaiser59ad0182018-02-16 13:01:36 -08002035 unsigned char decrypted_master_key[MAX_KEY_LEN];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002036 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002037 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002038 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002039 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002040 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002041 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002042 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002043 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002044 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002045 bool onlyCreateHeader = false;
2046 int fd = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002047
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002048 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002049 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2050 /* An encryption was underway and was interrupted */
2051 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2052 crypt_ftr.encrypted_upto = 0;
2053 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002054
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002055 /* At this point, we are in an inconsistent state. Until we successfully
2056 complete encryption, a reboot will leave us broken. So mark the
2057 encryption failed in case that happens.
2058 On successfully completing encryption, remove this flag */
2059 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002060
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002061 put_crypt_ftr_and_key(&crypt_ftr);
2062 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2063 if (!check_ftr_sha(&crypt_ftr)) {
2064 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2065 put_crypt_ftr_and_key(&crypt_ftr);
2066 goto error_unencrypted;
2067 }
2068
2069 /* Doing a reboot-encryption*/
2070 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2071 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2072 rebootEncryption = true;
2073 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002074 } else {
2075 // We don't want to accidentally reference invalid data.
2076 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002077 }
2078
2079 property_get("ro.crypto.state", encrypted_state, "");
2080 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2081 SLOGE("Device is already running encrypted, aborting");
2082 goto error_unencrypted;
2083 }
2084
2085 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002086 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2087 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002088
Ken Sumrall3ed82362011-01-28 23:31:16 -08002089 /* Get the size of the real block device */
Wei Wang4375f1b2017-02-24 17:43:01 -08002090 fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002091 if (fd == -1) {
2092 SLOGE("Cannot open block device %s\n", real_blkdev);
2093 goto error_unencrypted;
2094 }
2095 unsigned long nr_sec;
2096 get_blkdev_size(fd, &nr_sec);
2097 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002098 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2099 goto error_unencrypted;
2100 }
2101 close(fd);
2102
2103 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002104 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002105 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002106 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002107 if (fs_size_sec == 0)
2108 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2109
Paul Lawrence87999172014-02-20 12:21:31 -08002110 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002111
2112 if (fs_size_sec > max_fs_size_sec) {
2113 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2114 goto error_unencrypted;
2115 }
2116 }
2117
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002118 /* Get a wakelock as this may take a while, and we don't want the
2119 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2120 * wants to keep the screen on, it can grab a full wakelock.
2121 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002122 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002123 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2124
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002125 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002126 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002127 */
2128 property_set("vold.decrypt", "trigger_shutdown_framework");
2129 SLOGD("Just asked init to shut down class main\n");
2130
Jeff Sharkey9c484982015-03-31 10:35:33 -07002131 /* Ask vold to unmount all devices that it manages */
2132 if (vold_unmountAll()) {
2133 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002134 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002135
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002136 /* no_ui means we are being called from init, not settings.
2137 Now we always reboot from settings, so !no_ui means reboot
2138 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002139 if (!no_ui) {
2140 /* Try fallback, which is to reboot and try there */
2141 onlyCreateHeader = true;
2142 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2143 if (breadcrumb == 0) {
2144 SLOGE("Failed to create breadcrumb file");
2145 goto error_shutting_down;
2146 }
2147 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002148 }
2149
2150 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002151 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002152 /* Now that /data is unmounted, we need to mount a tmpfs
2153 * /data, set a property saying we're doing inplace encryption,
2154 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002155 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002156 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002157 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002158 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002159 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002160 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002161
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002162 /* restart the framework. */
2163 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002164 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002165
Ken Sumrall92736ef2012-10-17 20:57:14 -07002166 /* Ugh, shutting down the framework is not synchronous, so until it
2167 * can be fixed, this horrible hack will wait a moment for it all to
2168 * shut down before proceeding. Without it, some devices cannot
2169 * restart the graphics services.
2170 */
2171 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002172 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002173
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002174 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002175 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002176 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002177 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2178 goto error_shutting_down;
2179 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002180
Paul Lawrence87999172014-02-20 12:21:31 -08002181 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2182 crypt_ftr.fs_size = nr_sec
2183 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2184 } else {
2185 crypt_ftr.fs_size = nr_sec;
2186 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002187 /* At this point, we are in an inconsistent state. Until we successfully
2188 complete encryption, a reboot will leave us broken. So mark the
2189 encryption failed in case that happens.
2190 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002191 if (onlyCreateHeader) {
2192 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2193 } else {
2194 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2195 }
Paul Lawrence87999172014-02-20 12:21:31 -08002196 crypt_ftr.crypt_type = crypt_type;
Greg Kaiser57f9af62018-02-16 13:13:58 -08002197 strlcpy((char *)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(), MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002198
Paul Lawrence87999172014-02-20 12:21:31 -08002199 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002200 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2201 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002202 SLOGE("Cannot create encrypted master key\n");
2203 goto error_shutting_down;
2204 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002205
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002206 /* Replace scrypted intermediate key if we are preparing for a reboot */
2207 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002208 unsigned char fake_master_key[MAX_KEY_LEN];
2209 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002210 memset(fake_master_key, 0, sizeof(fake_master_key));
2211 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
2212 encrypted_fake_master_key, &crypt_ftr);
2213 }
2214
Paul Lawrence87999172014-02-20 12:21:31 -08002215 /* Write the key to the end of the partition */
2216 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002217
Paul Lawrence87999172014-02-20 12:21:31 -08002218 /* If any persistent data has been remembered, save it.
2219 * If none, create a valid empty table and save that.
2220 */
2221 if (!persist_data) {
Wei Wang4375f1b2017-02-24 17:43:01 -08002222 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002223 if (pdata) {
2224 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2225 persist_data = pdata;
2226 }
2227 }
2228 if (persist_data) {
2229 save_persistent_data();
2230 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002231 }
2232
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002233 if (onlyCreateHeader) {
2234 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002235 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002236 }
2237
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002238 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002239 /* startup service classes main and late_start */
2240 property_set("vold.decrypt", "trigger_restart_min_framework");
2241 SLOGD("Just triggered restart_min_framework\n");
2242
2243 /* OK, the framework is restarted and will soon be showing a
2244 * progress bar. Time to setup an encrypted mapping, and
2245 * either write a new filesystem, or encrypt in place updating
2246 * the progress bar as we work.
2247 */
2248 }
2249
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002250 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002251 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002252 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002253
Paul Lawrence87999172014-02-20 12:21:31 -08002254 /* If we are continuing, check checksums match */
2255 rc = 0;
2256 if (previously_encrypted_upto) {
2257 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2258 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002259
Paul Lawrence87999172014-02-20 12:21:31 -08002260 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2261 sizeof(hash_first_block)) != 0) {
2262 SLOGE("Checksums do not match - trigger wipe");
2263 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002264 }
2265 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002266
Paul Lawrence87999172014-02-20 12:21:31 -08002267 if (!rc) {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002268 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002269 previously_encrypted_upto);
2270 }
2271
2272 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002273 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002274 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2275 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002276 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002277 SLOGE("Error calculating checksum for continuing encryption");
2278 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002279 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002280 }
2281
2282 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002283 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002284
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002285 if (! rc) {
2286 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002287 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002288
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002289 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002290 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2291 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002292 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002293 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002294
Paul Lawrence6bfed202014-07-28 12:47:22 -07002295 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002296
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002297 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2298 char value[PROPERTY_VALUE_MAX];
2299 property_get("ro.crypto.state", value, "");
2300 if (!strcmp(value, "")) {
2301 /* default encryption - continue first boot sequence */
2302 property_set("ro.crypto.state", "encrypted");
2303 property_set("ro.crypto.type", "block");
2304 release_wake_lock(lockid);
2305 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2306 // Bring up cryptkeeper that will check the password and set it
2307 property_set("vold.decrypt", "trigger_shutdown_framework");
2308 sleep(2);
2309 property_set("vold.encrypt_progress", "");
2310 cryptfs_trigger_restart_min_framework();
2311 } else {
2312 cryptfs_check_passwd(DEFAULT_PASSWORD);
2313 cryptfs_restart_internal(1);
2314 }
2315 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002316 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002317 sleep(2); /* Give the UI a chance to show 100% progress */
2318 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002319 }
Paul Lawrence87999172014-02-20 12:21:31 -08002320 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002321 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002322 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002323 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002324 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002325 char value[PROPERTY_VALUE_MAX];
2326
Ken Sumrall319369a2012-06-27 16:30:18 -07002327 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002328 if (!strcmp(value, "1")) {
2329 /* wipe data if encryption failed */
2330 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002331 std::string err;
2332 const std::vector<std::string> options = {
2333 "--wipe_data\n--reason=cryptfs_enable_internal\n"
2334 };
2335 if (!write_bootloader_message(options, &err)) {
2336 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002337 }
Josh Gaofec44372017-08-28 13:22:55 -07002338 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002339 } else {
2340 /* set property to trigger dialog */
2341 property_set("vold.encrypt_progress", "error_partially_encrypted");
2342 release_wake_lock(lockid);
2343 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002344 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002345 }
2346
Ken Sumrall3ed82362011-01-28 23:31:16 -08002347 /* hrm, the encrypt step claims success, but the reboot failed.
2348 * This should not happen.
2349 * Set the property and return. Hope the framework can deal with it.
2350 */
2351 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002352 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002353 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002354
2355error_unencrypted:
2356 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002357 if (lockid[0]) {
2358 release_wake_lock(lockid);
2359 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002360 return -1;
2361
2362error_shutting_down:
2363 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2364 * but the framework is stopped and not restarted to show the error, so it's up to
2365 * vold to restart the system.
2366 */
2367 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Josh Gaofec44372017-08-28 13:22:55 -07002368 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002369
2370 /* shouldn't get here */
2371 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002372 if (lockid[0]) {
2373 release_wake_lock(lockid);
2374 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002375 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002376}
2377
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002378int cryptfs_enable(int type, const char* passwd, int no_ui) {
2379 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002380}
2381
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002382int cryptfs_enable_default(int no_ui) {
2383 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002384}
2385
2386int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002387{
Paul Crowley38132a12016-02-09 09:50:32 +00002388 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002389 SLOGE("cryptfs_changepw not valid for file encryption");
2390 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002391 }
2392
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002393 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002394 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002395
2396 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002397 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002398 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002399 return -1;
2400 }
2401
Paul Lawrencef4faa572014-01-29 13:31:03 -08002402 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2403 SLOGE("Invalid crypt_type %d", crypt_type);
2404 return -1;
2405 }
2406
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002407 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002408 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002409 SLOGE("Error getting crypt footer and key");
2410 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002411 }
2412
Paul Lawrencef4faa572014-01-29 13:31:03 -08002413 crypt_ftr.crypt_type = crypt_type;
2414
JP Abgrall933216c2015-02-11 13:44:32 -08002415 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08002416 : newpw,
2417 crypt_ftr.salt,
2418 saved_master_key,
2419 crypt_ftr.master_key,
2420 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002421 if (rc) {
2422 SLOGE("Encrypt master key failed: %d", rc);
2423 return -1;
2424 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002425 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002426 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002427
2428 return 0;
2429}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002430
Rubin Xu85c01f92014-10-13 12:49:54 +01002431static unsigned int persist_get_max_entries(int encrypted) {
2432 struct crypt_mnt_ftr crypt_ftr;
2433 unsigned int dsize;
2434 unsigned int max_persistent_entries;
2435
2436 /* If encrypted, use the values from the crypt_ftr, otherwise
2437 * use the values for the current spec.
2438 */
2439 if (encrypted) {
2440 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2441 return -1;
2442 }
2443 dsize = crypt_ftr.persist_data_size;
2444 } else {
2445 dsize = CRYPT_PERSIST_DATA_SIZE;
2446 }
2447
2448 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2449 sizeof(struct crypt_persist_entry);
2450
2451 return max_persistent_entries;
2452}
2453
2454static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002455{
2456 unsigned int i;
2457
2458 if (persist_data == NULL) {
2459 return -1;
2460 }
2461 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2462 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2463 /* We found it! */
2464 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2465 return 0;
2466 }
2467 }
2468
2469 return -1;
2470}
2471
Rubin Xu85c01f92014-10-13 12:49:54 +01002472static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002473{
2474 unsigned int i;
2475 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002476 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002477
2478 if (persist_data == NULL) {
2479 return -1;
2480 }
2481
Rubin Xu85c01f92014-10-13 12:49:54 +01002482 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002483
2484 num = persist_data->persist_valid_entries;
2485
2486 for (i = 0; i < num; i++) {
2487 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2488 /* We found an existing entry, update it! */
2489 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2490 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2491 return 0;
2492 }
2493 }
2494
2495 /* We didn't find it, add it to the end, if there is room */
2496 if (persist_data->persist_valid_entries < max_persistent_entries) {
2497 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2498 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2499 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2500 persist_data->persist_valid_entries++;
2501 return 0;
2502 }
2503
2504 return -1;
2505}
2506
Rubin Xu85c01f92014-10-13 12:49:54 +01002507/**
2508 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2509 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2510 */
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002511int match_multi_entry(const char *key, const char *field, unsigned index) {
2512 std::string key_ = key;
2513 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002514
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002515 std::string parsed_field;
2516 unsigned parsed_index;
2517
2518 std::string::size_type split = key_.find_last_of('_');
2519 if (split == std::string::npos) {
2520 parsed_field = key_;
2521 parsed_index = 0;
2522 } else {
2523 parsed_field = key_.substr(0, split);
2524 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002525 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002526
2527 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002528}
2529
2530/*
2531 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2532 * remaining entries starting from index will be deleted.
2533 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2534 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2535 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2536 *
2537 */
2538static int persist_del_keys(const char *fieldname, unsigned index)
2539{
2540 unsigned int i;
2541 unsigned int j;
2542 unsigned int num;
2543
2544 if (persist_data == NULL) {
2545 return PERSIST_DEL_KEY_ERROR_OTHER;
2546 }
2547
2548 num = persist_data->persist_valid_entries;
2549
2550 j = 0; // points to the end of non-deleted entries.
2551 // Filter out to-be-deleted entries in place.
2552 for (i = 0; i < num; i++) {
2553 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2554 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2555 j++;
2556 }
2557 }
2558
2559 if (j < num) {
2560 persist_data->persist_valid_entries = j;
2561 // Zeroise the remaining entries
2562 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2563 return PERSIST_DEL_KEY_OK;
2564 } else {
2565 // Did not find an entry matching the given fieldname
2566 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2567 }
2568}
2569
2570static int persist_count_keys(const char *fieldname)
2571{
2572 unsigned int i;
2573 unsigned int count;
2574
2575 if (persist_data == NULL) {
2576 return -1;
2577 }
2578
2579 count = 0;
2580 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2581 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2582 count++;
2583 }
2584 }
2585
2586 return count;
2587}
2588
Ken Sumrall160b4d62013-04-22 12:15:39 -07002589/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002590int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002591{
Paul Crowley38132a12016-02-09 09:50:32 +00002592 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002593 SLOGE("Cannot get field when file encrypted");
2594 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002595 }
2596
Ken Sumrall160b4d62013-04-22 12:15:39 -07002597 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002598 /* CRYPTO_GETFIELD_OK is success,
2599 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2600 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2601 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002602 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002603 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2604 int i;
2605 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002606
2607 if (persist_data == NULL) {
2608 load_persistent_data();
2609 if (persist_data == NULL) {
2610 SLOGE("Getfield error, cannot load persistent data");
2611 goto out;
2612 }
2613 }
2614
Rubin Xu85c01f92014-10-13 12:49:54 +01002615 // Read value from persistent entries. If the original value is split into multiple entries,
2616 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002617 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002618 // We found it, copy it to the caller's buffer and keep going until all entries are read.
2619 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
2620 // value too small
2621 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2622 goto out;
2623 }
2624 rc = CRYPTO_GETFIELD_OK;
2625
2626 for (i = 1; /* break explicitly */; i++) {
2627 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
2628 (int) sizeof(temp_field)) {
2629 // If the fieldname is very long, we stop as soon as it begins to overflow the
2630 // maximum field length. At this point we have in fact fully read out the original
2631 // value because cryptfs_setfield would not allow fields with longer names to be
2632 // written in the first place.
2633 break;
2634 }
2635 if (!persist_get_key(temp_field, temp_value)) {
2636 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2637 // value too small.
2638 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2639 goto out;
2640 }
2641 } else {
2642 // Exhaust all entries.
2643 break;
2644 }
2645 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002646 } else {
2647 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002648 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002649 }
2650
2651out:
2652 return rc;
2653}
2654
2655/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002656int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002657{
Paul Crowley38132a12016-02-09 09:50:32 +00002658 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002659 SLOGE("Cannot set field when file encrypted");
2660 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002661 }
2662
Ken Sumrall160b4d62013-04-22 12:15:39 -07002663 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002664 /* 0 is success, negative values are error */
2665 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002666 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002667 unsigned int field_id;
2668 char temp_field[PROPERTY_KEY_MAX];
2669 unsigned int num_entries;
2670 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002671
2672 if (persist_data == NULL) {
2673 load_persistent_data();
2674 if (persist_data == NULL) {
2675 SLOGE("Setfield error, cannot load persistent data");
2676 goto out;
2677 }
2678 }
2679
2680 property_get("ro.crypto.state", encrypted_state, "");
2681 if (!strcmp(encrypted_state, "encrypted") ) {
2682 encrypted = 1;
2683 }
2684
Rubin Xu85c01f92014-10-13 12:49:54 +01002685 // Compute the number of entries required to store value, each entry can store up to
2686 // (PROPERTY_VALUE_MAX - 1) chars
2687 if (strlen(value) == 0) {
2688 // Empty value also needs one entry to store.
2689 num_entries = 1;
2690 } else {
2691 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2692 }
2693
2694 max_keylen = strlen(fieldname);
2695 if (num_entries > 1) {
2696 // Need an extra "_%d" suffix.
2697 max_keylen += 1 + log10(num_entries);
2698 }
2699 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2700 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002701 goto out;
2702 }
2703
Rubin Xu85c01f92014-10-13 12:49:54 +01002704 // Make sure we have enough space to write the new value
2705 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2706 persist_get_max_entries(encrypted)) {
2707 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2708 goto out;
2709 }
2710
2711 // Now that we know persist_data has enough space for value, let's delete the old field first
2712 // to make up space.
2713 persist_del_keys(fieldname, 0);
2714
2715 if (persist_set_key(fieldname, value, encrypted)) {
2716 // fail to set key, should not happen as we have already checked the available space
2717 SLOGE("persist_set_key() error during setfield()");
2718 goto out;
2719 }
2720
2721 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002722 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002723
2724 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2725 // fail to set key, should not happen as we have already checked the available space.
2726 SLOGE("persist_set_key() error during setfield()");
2727 goto out;
2728 }
2729 }
2730
Ken Sumrall160b4d62013-04-22 12:15:39 -07002731 /* If we are running encrypted, save the persistent data now */
2732 if (encrypted) {
2733 if (save_persistent_data()) {
2734 SLOGE("Setfield error, cannot save persistent data");
2735 goto out;
2736 }
2737 }
2738
Rubin Xu85c01f92014-10-13 12:49:54 +01002739 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002740
2741out:
2742 return rc;
2743}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002744
2745/* Checks userdata. Attempt to mount the volume if default-
2746 * encrypted.
2747 * On success trigger next init phase and return 0.
2748 * Currently do not handle failure - see TODO below.
2749 */
2750int cryptfs_mount_default_encrypted(void)
2751{
Paul Lawrence84274cc2016-04-15 15:41:33 -07002752 int crypt_type = cryptfs_get_password_type();
2753 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2754 SLOGE("Bad crypt type - error");
2755 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2756 SLOGD("Password is not default - "
2757 "starting min framework to prompt");
2758 property_set("vold.decrypt", "trigger_restart_min_framework");
2759 return 0;
2760 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2761 SLOGD("Password is default - restarting filesystem");
2762 cryptfs_restart_internal(0);
2763 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002764 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002765 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002766 }
2767
Paul Lawrence6bfed202014-07-28 12:47:22 -07002768 /** Corrupt. Allow us to boot into framework, which will detect bad
2769 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002770 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002771 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002772 return 0;
2773}
2774
2775/* Returns type of the password, default, pattern, pin or password.
2776 */
2777int cryptfs_get_password_type(void)
2778{
Paul Crowley38132a12016-02-09 09:50:32 +00002779 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002780 SLOGE("cryptfs_get_password_type not valid for file encryption");
2781 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002782 }
2783
Paul Lawrencef4faa572014-01-29 13:31:03 -08002784 struct crypt_mnt_ftr crypt_ftr;
2785
2786 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2787 SLOGE("Error getting crypt footer and key\n");
2788 return -1;
2789 }
2790
Paul Lawrence6bfed202014-07-28 12:47:22 -07002791 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2792 return -1;
2793 }
2794
Paul Lawrencef4faa572014-01-29 13:31:03 -08002795 return crypt_ftr.crypt_type;
2796}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002797
Paul Lawrence05335c32015-03-05 09:46:23 -08002798const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002799{
Paul Crowley38132a12016-02-09 09:50:32 +00002800 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002801 SLOGE("cryptfs_get_password not valid for file encryption");
2802 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002803 }
2804
Paul Lawrence399317e2014-03-10 13:20:50 -07002805 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002806 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002807 if (now.tv_sec < password_expiry_time) {
2808 return password;
2809 } else {
2810 cryptfs_clear_password();
2811 return 0;
2812 }
2813}
2814
2815void cryptfs_clear_password()
2816{
2817 if (password) {
2818 size_t len = strlen(password);
2819 memset(password, 0, len);
2820 free(password);
2821 password = 0;
2822 password_expiry_time = 0;
2823 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002824}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002825
Paul Lawrence0c247462015-10-29 10:30:57 -07002826int cryptfs_isConvertibleToFBE()
2827{
Paul Crowleye2ee1522017-09-26 14:05:26 -07002828 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Paul Lawrence0c247462015-10-29 10:30:57 -07002829 return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
2830}