blob: d0de553e4ea8b687ca3803aa4e4b1c2dca2af14c [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 Kaiserfa099612018-02-14 11:26:00 -080075#define 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 Kaiserfa099612018-02-14 11:26:00 -0800111static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -0700112static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -0600113static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700114static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800115
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700116/* Should we use keymaster? */
117static int keymaster_check_compatibility()
118{
Janis Danisevskis015ec302017-01-31 11:31:08 +0000119 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700120}
121
122/* Create a new keymaster key and store it in this footer */
123static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
124{
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800125 if (ftr->keymaster_blob_size) {
126 SLOGI("Already have key");
127 return 0;
128 }
129
Janis Danisevskis015ec302017-01-31 11:31:08 +0000130 int rc = keymaster_create_key_for_cryptfs_scrypt(RSA_KEY_SIZE, RSA_EXPONENT,
131 KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
132 &ftr->keymaster_blob_size);
133 if (rc) {
134 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800135 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000136 ftr->keymaster_blob_size = 0;
137 }
138 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700139 return -1;
140 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000141 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700142}
143
Shawn Willdene17a9c42014-09-08 13:04:08 -0600144/* This signs the given object using the keymaster key. */
145static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600146 const unsigned char *object,
147 const size_t object_size,
148 unsigned char **signature,
149 size_t *signature_size)
150{
Shawn Willden47ba10d2014-09-03 17:07:06 -0600151 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600152 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600153 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600154
Shawn Willdene17a9c42014-09-08 13:04:08 -0600155 // To sign a message with RSA, the message must satisfy two
156 // constraints:
157 //
158 // 1. The message, when interpreted as a big-endian numeric value, must
159 // be strictly less than the public modulus of the RSA key. Note
160 // that because the most significant bit of the public modulus is
161 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
162 // key), an n-bit message with most significant bit 0 always
163 // satisfies this requirement.
164 //
165 // 2. The message must have the same length in bits as the public
166 // modulus of the RSA key. This requirement isn't mathematically
167 // necessary, but is necessary to ensure consistency in
168 // implementations.
169 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600170 case KDF_SCRYPT_KEYMASTER:
171 // This ensures the most significant byte of the signed message
172 // is zero. We could have zero-padded to the left instead, but
173 // this approach is slightly more robust against changes in
174 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600175 // so) because we really should be using a proper deterministic
176 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800177 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600178 SLOGI("Signing safely-padded object");
179 break;
180 default:
181 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000182 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600183 }
Paul Crowley73473332017-11-21 15:43:51 -0800184 for (;;) {
185 auto result = keymaster_sign_object_for_cryptfs_scrypt(
186 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
187 to_sign_size, signature, signature_size);
188 switch (result) {
189 case KeymasterSignResult::ok:
190 return 0;
191 case KeymasterSignResult::upgrade:
192 break;
193 default:
194 return -1;
195 }
196 SLOGD("Upgrading key");
197 if (keymaster_upgrade_key_for_cryptfs_scrypt(
198 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
199 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
200 &ftr->keymaster_blob_size) != 0) {
201 SLOGE("Failed to upgrade key");
202 return -1;
203 }
204 if (put_crypt_ftr_and_key(ftr) != 0) {
205 SLOGE("Failed to write upgraded key to disk");
206 }
207 SLOGD("Key upgraded successfully");
208 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600209}
210
Paul Lawrence399317e2014-03-10 13:20:50 -0700211/* Store password when userdata is successfully decrypted and mounted.
212 * Cleared by cryptfs_clear_password
213 *
214 * To avoid a double prompt at boot, we need to store the CryptKeeper
215 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
216 * Since the entire framework is torn down and rebuilt after encryption,
217 * we have to use a daemon or similar to store the password. Since vold
218 * is secured against IPC except from system processes, it seems a reasonable
219 * place to store this.
220 *
221 * password should be cleared once it has been used.
222 *
223 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800224 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700225static char* password = 0;
226static int password_expiry_time = 0;
227static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800228
Josh Gaofec44372017-08-28 13:22:55 -0700229enum class RebootType {reboot, recovery, shutdown};
230static void cryptfs_reboot(RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700231{
Josh Gaofec44372017-08-28 13:22:55 -0700232 switch (rt) {
233 case RebootType::reboot:
Paul Lawrence87999172014-02-20 12:21:31 -0800234 property_set(ANDROID_RB_PROPERTY, "reboot");
235 break;
236
Josh Gaofec44372017-08-28 13:22:55 -0700237 case RebootType::recovery:
Paul Lawrence87999172014-02-20 12:21:31 -0800238 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
239 break;
240
Josh Gaofec44372017-08-28 13:22:55 -0700241 case RebootType::shutdown:
Paul Lawrence87999172014-02-20 12:21:31 -0800242 property_set(ANDROID_RB_PROPERTY, "shutdown");
243 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700244 }
Paul Lawrence87999172014-02-20 12:21:31 -0800245
Ken Sumralladfba362013-06-04 16:37:52 -0700246 sleep(20);
247
248 /* Shouldn't get here, reboot should happen before sleep times out */
249 return;
250}
251
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800252static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
253{
254 memset(io, 0, dataSize);
255 io->data_size = dataSize;
256 io->data_start = sizeof(struct dm_ioctl);
257 io->version[0] = 4;
258 io->version[1] = 0;
259 io->version[2] = 0;
260 io->flags = flags;
261 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100262 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800263 }
264}
265
Kenny Rootc4c70f12013-06-14 12:11:38 -0700266/**
267 * Gets the default device scrypt parameters for key derivation time tuning.
268 * The parameters should lead to about one second derivation time for the
269 * given device.
270 */
271static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700272 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000273 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700274
Paul Crowley63c18d32016-02-10 14:02:47 +0000275 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
276 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
277 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
278 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700279 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000280 ftr->N_factor = Nf;
281 ftr->r_factor = rf;
282 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700283}
284
Ken Sumrall3ed82362011-01-28 23:31:16 -0800285static unsigned int get_fs_size(char *dev)
286{
287 int fd, block_size;
288 struct ext4_super_block sb;
289 off64_t len;
290
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700291 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800292 SLOGE("Cannot open device to get filesystem size ");
293 return 0;
294 }
295
296 if (lseek64(fd, 1024, SEEK_SET) < 0) {
297 SLOGE("Cannot seek to superblock");
298 return 0;
299 }
300
301 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
302 SLOGE("Cannot read superblock");
303 return 0;
304 }
305
306 close(fd);
307
Daniel Rosenberge82df162014-08-15 22:19:23 +0000308 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
309 SLOGE("Not a valid ext4 superblock");
310 return 0;
311 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800312 block_size = 1024 << sb.s_log_block_size;
313 /* compute length in bytes */
314 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
315
316 /* return length in sectors */
317 return (unsigned int) (len / 512);
318}
319
Ken Sumrall160b4d62013-04-22 12:15:39 -0700320static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
321{
322 static int cached_data = 0;
323 static off64_t cached_off = 0;
324 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
325 int fd;
326 char key_loc[PROPERTY_VALUE_MAX];
327 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700328 int rc = -1;
329
330 if (!cached_data) {
Paul Crowleye2ee1522017-09-26 14:05:26 -0700331 fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700332
333 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700334 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700335 SLOGE("Cannot open real block device %s\n", real_blkdev);
336 return -1;
337 }
338
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900339 unsigned long nr_sec = 0;
340 get_blkdev_size(fd, &nr_sec);
341 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700342 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
343 * encryption info footer and key, and plenty of bytes to spare for future
344 * growth.
345 */
346 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
347 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
348 cached_data = 1;
349 } else {
350 SLOGE("Cannot get size of block device %s\n", real_blkdev);
351 }
352 close(fd);
353 } else {
354 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
355 cached_off = 0;
356 cached_data = 1;
357 }
358 }
359
360 if (cached_data) {
361 if (metadata_fname) {
362 *metadata_fname = cached_metadata_fname;
363 }
364 if (off) {
365 *off = cached_off;
366 }
367 rc = 0;
368 }
369
370 return rc;
371}
372
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800373/* Set sha256 checksum in structure */
374static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr)
375{
376 SHA256_CTX c;
377 SHA256_Init(&c);
378 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
379 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
380 SHA256_Final(crypt_ftr->sha256, &c);
381}
382
Ken Sumralle8744072011-01-18 22:01:55 -0800383/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800384 * update the failed mount count but not change the key.
385 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700386static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800387{
388 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800389 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700390 /* starting_off is set to the SEEK_SET offset
391 * where the crypto structure starts
392 */
393 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800394 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700395 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700396 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800397
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800398 set_ftr_sha(crypt_ftr);
399
Ken Sumrall160b4d62013-04-22 12:15:39 -0700400 if (get_crypt_ftr_info(&fname, &starting_off)) {
401 SLOGE("Unable to get crypt_ftr_info\n");
402 return -1;
403 }
404 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700405 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700406 return -1;
407 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700408 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700409 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700410 return -1;
411 }
412
413 /* Seek to the start of the crypt footer */
414 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
415 SLOGE("Cannot seek to real block device footer\n");
416 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800417 }
418
419 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
420 SLOGE("Cannot write real block device footer\n");
421 goto errout;
422 }
423
Ken Sumrall3be890f2011-09-14 16:53:46 -0700424 fstat(fd, &statbuf);
425 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700426 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700427 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800428 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800429 goto errout;
430 }
431 }
432
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800433 /* Success! */
434 rc = 0;
435
436errout:
437 close(fd);
438 return rc;
439
440}
441
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800442static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr)
443{
444 struct crypt_mnt_ftr copy;
445 memcpy(&copy, crypt_ftr, sizeof(copy));
446 set_ftr_sha(&copy);
447 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
448}
449
Ken Sumrall160b4d62013-04-22 12:15:39 -0700450static inline int unix_read(int fd, void* buff, int len)
451{
452 return TEMP_FAILURE_RETRY(read(fd, buff, len));
453}
454
455static inline int unix_write(int fd, const void* buff, int len)
456{
457 return TEMP_FAILURE_RETRY(write(fd, buff, len));
458}
459
460static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
461{
462 memset(pdata, 0, len);
463 pdata->persist_magic = PERSIST_DATA_MAGIC;
464 pdata->persist_valid_entries = 0;
465}
466
467/* A routine to update the passed in crypt_ftr to the lastest version.
468 * fd is open read/write on the device that holds the crypto footer and persistent
469 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
470 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
471 */
472static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
473{
Kenny Root7434b312013-06-14 11:29:53 -0700474 int orig_major = crypt_ftr->major_version;
475 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700476
Kenny Root7434b312013-06-14 11:29:53 -0700477 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
478 struct crypt_persist_data *pdata;
479 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700480
Kenny Rootc4c70f12013-06-14 12:11:38 -0700481 SLOGW("upgrading crypto footer to 1.1");
482
Wei Wang4375f1b2017-02-24 17:43:01 -0800483 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700484 if (pdata == NULL) {
485 SLOGE("Cannot allocate persisent data\n");
486 return;
487 }
488 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
489
490 /* Need to initialize the persistent data area */
491 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
492 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100493 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700494 return;
495 }
496 /* Write all zeros to the first copy, making it invalid */
497 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
498
499 /* Write a valid but empty structure to the second copy */
500 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
501 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
502
503 /* Update the footer */
504 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
505 crypt_ftr->persist_data_offset[0] = pdata_offset;
506 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
507 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100508 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700509 }
510
Paul Lawrencef4faa572014-01-29 13:31:03 -0800511 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700512 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800513 /* But keep the old kdf_type.
514 * It will get updated later to KDF_SCRYPT after the password has been verified.
515 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700516 crypt_ftr->kdf_type = KDF_PBKDF2;
517 get_device_scrypt_params(crypt_ftr);
518 crypt_ftr->minor_version = 2;
519 }
520
Paul Lawrencef4faa572014-01-29 13:31:03 -0800521 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
522 SLOGW("upgrading crypto footer to 1.3");
523 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
524 crypt_ftr->minor_version = 3;
525 }
526
Kenny Root7434b312013-06-14 11:29:53 -0700527 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
528 if (lseek64(fd, offset, SEEK_SET) == -1) {
529 SLOGE("Cannot seek to crypt footer\n");
530 return;
531 }
532 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700533 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700534}
535
536
537static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800538{
539 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800540 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700541 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800542 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700543 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700544 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800545
Ken Sumrall160b4d62013-04-22 12:15:39 -0700546 if (get_crypt_ftr_info(&fname, &starting_off)) {
547 SLOGE("Unable to get crypt_ftr_info\n");
548 return -1;
549 }
550 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700551 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700552 return -1;
553 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700554 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700555 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700556 return -1;
557 }
558
559 /* Make sure it's 16 Kbytes in length */
560 fstat(fd, &statbuf);
561 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
562 SLOGE("footer file %s is not the expected size!\n", fname);
563 goto errout;
564 }
565
566 /* Seek to the start of the crypt footer */
567 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
568 SLOGE("Cannot seek to real block device footer\n");
569 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800570 }
571
572 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
573 SLOGE("Cannot read real block device footer\n");
574 goto errout;
575 }
576
577 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700578 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800579 goto errout;
580 }
581
Kenny Rootc96a5f82013-06-14 12:08:28 -0700582 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
583 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
584 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800585 goto errout;
586 }
587
Kenny Rootc96a5f82013-06-14 12:08:28 -0700588 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
589 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
590 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800591 }
592
Ken Sumrall160b4d62013-04-22 12:15:39 -0700593 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
594 * copy on disk before returning.
595 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700596 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700597 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800598 }
599
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800600 /* Success! */
601 rc = 0;
602
603errout:
604 close(fd);
605 return rc;
606}
607
Ken Sumrall160b4d62013-04-22 12:15:39 -0700608static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
609{
610 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
611 crypt_ftr->persist_data_offset[1]) {
612 SLOGE("Crypt_ftr persist data regions overlap");
613 return -1;
614 }
615
616 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
617 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
618 return -1;
619 }
620
621 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
622 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
623 CRYPT_FOOTER_OFFSET) {
624 SLOGE("Persistent data extends past crypto footer");
625 return -1;
626 }
627
628 return 0;
629}
630
631static int load_persistent_data(void)
632{
633 struct crypt_mnt_ftr crypt_ftr;
634 struct crypt_persist_data *pdata = NULL;
635 char encrypted_state[PROPERTY_VALUE_MAX];
636 char *fname;
637 int found = 0;
638 int fd;
639 int ret;
640 int i;
641
642 if (persist_data) {
643 /* Nothing to do, we've already loaded or initialized it */
644 return 0;
645 }
646
647
648 /* If not encrypted, just allocate an empty table and initialize it */
649 property_get("ro.crypto.state", encrypted_state, "");
650 if (strcmp(encrypted_state, "encrypted") ) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800651 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700652 if (pdata) {
653 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
654 persist_data = pdata;
655 return 0;
656 }
657 return -1;
658 }
659
660 if(get_crypt_ftr_and_key(&crypt_ftr)) {
661 return -1;
662 }
663
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700664 if ((crypt_ftr.major_version < 1)
665 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700666 SLOGE("Crypt_ftr version doesn't support persistent data");
667 return -1;
668 }
669
670 if (get_crypt_ftr_info(&fname, NULL)) {
671 return -1;
672 }
673
674 ret = validate_persistent_data_storage(&crypt_ftr);
675 if (ret) {
676 return -1;
677 }
678
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700679 fd = open(fname, O_RDONLY|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700680 if (fd < 0) {
681 SLOGE("Cannot open %s metadata file", fname);
682 return -1;
683 }
684
Wei Wang4375f1b2017-02-24 17:43:01 -0800685 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800686 if (pdata == NULL) {
687 SLOGE("Cannot allocate memory for persistent data");
688 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700689 }
690
691 for (i = 0; i < 2; i++) {
692 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
693 SLOGE("Cannot seek to read persistent data on %s", fname);
694 goto err2;
695 }
696 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
697 SLOGE("Error reading persistent data on iteration %d", i);
698 goto err2;
699 }
700 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
701 found = 1;
702 break;
703 }
704 }
705
706 if (!found) {
707 SLOGI("Could not find valid persistent data, creating");
708 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
709 }
710
711 /* Success */
712 persist_data = pdata;
713 close(fd);
714 return 0;
715
716err2:
717 free(pdata);
718
719err:
720 close(fd);
721 return -1;
722}
723
724static int save_persistent_data(void)
725{
726 struct crypt_mnt_ftr crypt_ftr;
727 struct crypt_persist_data *pdata;
728 char *fname;
729 off64_t write_offset;
730 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700731 int fd;
732 int ret;
733
734 if (persist_data == NULL) {
735 SLOGE("No persistent data to save");
736 return -1;
737 }
738
739 if(get_crypt_ftr_and_key(&crypt_ftr)) {
740 return -1;
741 }
742
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700743 if ((crypt_ftr.major_version < 1)
744 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700745 SLOGE("Crypt_ftr version doesn't support persistent data");
746 return -1;
747 }
748
749 ret = validate_persistent_data_storage(&crypt_ftr);
750 if (ret) {
751 return -1;
752 }
753
754 if (get_crypt_ftr_info(&fname, NULL)) {
755 return -1;
756 }
757
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700758 fd = open(fname, O_RDWR|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700759 if (fd < 0) {
760 SLOGE("Cannot open %s metadata file", fname);
761 return -1;
762 }
763
Wei Wang4375f1b2017-02-24 17:43:01 -0800764 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700765 if (pdata == NULL) {
766 SLOGE("Cannot allocate persistant data");
767 goto err;
768 }
769
770 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
771 SLOGE("Cannot seek to read persistent data on %s", fname);
772 goto err2;
773 }
774
775 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
776 SLOGE("Error reading persistent data before save");
777 goto err2;
778 }
779
780 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
781 /* The first copy is the curent valid copy, so write to
782 * the second copy and erase this one */
783 write_offset = crypt_ftr.persist_data_offset[1];
784 erase_offset = crypt_ftr.persist_data_offset[0];
785 } else {
786 /* The second copy must be the valid copy, so write to
787 * the first copy, and erase the second */
788 write_offset = crypt_ftr.persist_data_offset[0];
789 erase_offset = crypt_ftr.persist_data_offset[1];
790 }
791
792 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100793 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700794 SLOGE("Cannot seek to write persistent data");
795 goto err2;
796 }
797 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
798 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100799 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700800 SLOGE("Cannot seek to erase previous persistent data");
801 goto err2;
802 }
803 fsync(fd);
804 memset(pdata, 0, crypt_ftr.persist_data_size);
805 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
806 (int) crypt_ftr.persist_data_size) {
807 SLOGE("Cannot write to erase previous persistent data");
808 goto err2;
809 }
810 fsync(fd);
811 } else {
812 SLOGE("Cannot write to save persistent data");
813 goto err2;
814 }
815
816 /* Success */
817 free(pdata);
818 close(fd);
819 return 0;
820
821err2:
822 free(pdata);
823err:
824 close(fd);
825 return -1;
826}
827
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800828/* Convert a binary key of specified length into an ascii hex string equivalent,
829 * without the leading 0x and with null termination
830 */
Jeff Sharkey9c484982015-03-31 10:35:33 -0700831static void convert_key_to_hex_ascii(const unsigned char *master_key,
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700832 unsigned int keysize, char *master_key_ascii) {
833 unsigned int i, a;
834 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800835
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700836 for (i=0, a=0; i<keysize; i++, a+=2) {
837 /* For each byte, write out two ascii hex digits */
838 nibble = (master_key[i] >> 4) & 0xf;
839 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800840
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700841 nibble = master_key[i] & 0xf;
842 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
843 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800844
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700845 /* Add the null termination */
846 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800847
848}
849
Jeff Sharkey9c484982015-03-31 10:35:33 -0700850static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
851 const unsigned char *master_key, const char *real_blk_name,
852 const char *name, int fd, const char *extra_params) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800853 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800854 struct dm_ioctl *io;
855 struct dm_target_spec *tgt;
856 char *crypt_params;
Greg Kaiserfa099612018-02-14 11:26:00 -0800857 // We can't assume the key is only KEY_LEN_BYTES. But we do know its limit
Greg Kaiser1452b272018-02-09 16:11:38 -0800858 // due to the crypt_mnt_ftr struct. We need two ASCII characters to represent
859 // each byte, and need space for the '\0' terminator.
860 char master_key_ascii[sizeof(crypt_ftr->master_key) * 2 + 1];
George Burgess IV605d7ae2016-02-29 13:39:17 -0800861 size_t buff_offset;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800862 int i;
863
864 io = (struct dm_ioctl *) buffer;
865
866 /* Load the mapping table for this device */
867 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
868
869 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
870 io->target_count = 1;
871 tgt->status = 0;
872 tgt->sector_start = 0;
873 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -0700874 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800875
876 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
877 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800878
879 buff_offset = crypt_params - buffer;
Paul Crowley5afbc622017-11-27 09:42:17 -0800880 SLOGI("Extra parameters for dm_crypt: %s\n", extra_params);
George Burgess IV605d7ae2016-02-29 13:39:17 -0800881 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
882 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name,
883 extra_params);
Ken Sumralldb5e0262013-02-05 17:39:48 -0800884 crypt_params += strlen(crypt_params) + 1;
885 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
886 tgt->next = crypt_params - buffer;
887
888 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
889 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
890 break;
891 }
892 usleep(500000);
893 }
894
895 if (i == TABLE_LOAD_RETRIES) {
896 /* We failed to load the table, return an error */
897 return -1;
898 } else {
899 return i + 1;
900 }
901}
902
903
904static int get_dm_crypt_version(int fd, const char *name, int *version)
905{
906 char buffer[DM_CRYPT_BUF_SIZE];
907 struct dm_ioctl *io;
908 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800909
910 io = (struct dm_ioctl *) buffer;
911
912 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
913
914 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
915 return -1;
916 }
917
918 /* Iterate over the returned versions, looking for name of "crypt".
919 * When found, get and return the version.
920 */
921 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
922 while (v->next) {
923 if (! strcmp(v->name, "crypt")) {
924 /* We found the crypt driver, return the version, and get out */
925 version[0] = v->version[0];
926 version[1] = v->version[1];
927 version[2] = v->version[2];
928 return 0;
929 }
930 v = (struct dm_target_versions *)(((char *)v) + v->next);
931 }
932
933 return -1;
934}
935
Paul Crowley5afbc622017-11-27 09:42:17 -0800936static std::string extra_params_as_string(const std::vector<std::string>& extra_params_vec) {
937 if (extra_params_vec.empty()) return "";
938 std::string extra_params = std::to_string(extra_params_vec.size());
939 for (const auto& p : extra_params_vec) {
940 extra_params.append(" ");
941 extra_params.append(p);
942 }
943 return extra_params;
944}
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800945
Paul Crowley5afbc622017-11-27 09:42:17 -0800946static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
947 const char* real_blk_name, char* crypto_blk_name, const char* name,
948 uint32_t flags) {
949 char buffer[DM_CRYPT_BUF_SIZE];
950 struct dm_ioctl* io;
951 unsigned int minor;
952 int fd = 0;
953 int err;
954 int retval = -1;
955 int version[3];
956 int load_count;
957 std::vector<std::string> extra_params_vec;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800958
Paul Crowley5afbc622017-11-27 09:42:17 -0800959 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
960 SLOGE("Cannot open device-mapper\n");
961 goto errout;
962 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800963
Paul Crowley5afbc622017-11-27 09:42:17 -0800964 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800965
Paul Crowley5afbc622017-11-27 09:42:17 -0800966 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
967 err = ioctl(fd, DM_DEV_CREATE, io);
968 if (err) {
969 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
970 goto errout;
971 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800972
Paul Crowley5afbc622017-11-27 09:42:17 -0800973 /* Get the device status, in particular, the name of it's device file */
974 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
975 if (ioctl(fd, DM_DEV_STATUS, io)) {
976 SLOGE("Cannot retrieve dm-crypt device status\n");
977 goto errout;
978 }
979 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
980 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
Ken Sumralle919efe2012-09-29 17:07:41 -0700981
Paul Crowley5afbc622017-11-27 09:42:17 -0800982 if (!get_dm_crypt_version(fd, name, version)) {
983 /* Support for allow_discards was added in version 1.11.0 */
984 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
985 extra_params_vec.emplace_back("allow_discards");
986 }
987 }
988 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
989 extra_params_vec.emplace_back("allow_encrypt_override");
990 }
991 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
992 extra_params_as_string(extra_params_vec).c_str());
993 if (load_count < 0) {
994 SLOGE("Cannot load dm-crypt mapping table.\n");
995 goto errout;
996 } else if (load_count > 1) {
997 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
998 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800999
Paul Crowley5afbc622017-11-27 09:42:17 -08001000 /* Resume this device to activate it */
1001 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001002
Paul Crowley5afbc622017-11-27 09:42:17 -08001003 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1004 SLOGE("Cannot resume the dm-crypt device\n");
1005 goto errout;
1006 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001007
Paul Crowley5afbc622017-11-27 09:42:17 -08001008 /* We made it here with no errors. Woot! */
1009 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001010
1011errout:
1012 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1013
1014 return retval;
1015}
1016
Wei Wang4375f1b2017-02-24 17:43:01 -08001017static int delete_crypto_blk_dev(const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001018{
1019 int fd;
1020 char buffer[DM_CRYPT_BUF_SIZE];
1021 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001022 int retval = -1;
1023
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001024 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001025 SLOGE("Cannot open device-mapper\n");
1026 goto errout;
1027 }
1028
1029 io = (struct dm_ioctl *) buffer;
1030
1031 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1032 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1033 SLOGE("Cannot remove dm-crypt device\n");
1034 goto errout;
1035 }
1036
1037 /* We made it here with no errors. Woot! */
1038 retval = 0;
1039
1040errout:
1041 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1042
1043 return retval;
1044
1045}
1046
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001047static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001048 unsigned char *ikey, void *params UNUSED)
1049{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001050 SLOGI("Using pbkdf2 for cryptfs KDF");
1051
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001052 /* Turn the password into a key and IV that can decrypt the master key */
Adam Langleybf0d9722015-11-04 14:51:39 -08001053 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001054 HASH_COUNT, INTERMEDIATE_BUF_SIZE,
Adam Langleybf0d9722015-11-04 14:51:39 -08001055 ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001056}
1057
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001058static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001059 unsigned char *ikey, void *params)
1060{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001061 SLOGI("Using scrypt for cryptfs KDF");
1062
Kenny Rootc4c70f12013-06-14 12:11:38 -07001063 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1064
1065 int N = 1 << ftr->N_factor;
1066 int r = 1 << ftr->r_factor;
1067 int p = 1 << ftr->p_factor;
1068
1069 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001070 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1071 salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001072 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001073
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001074 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001075}
1076
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001077static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1078 unsigned char *ikey, void *params)
1079{
1080 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1081
1082 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001083 size_t signature_size;
1084 unsigned char* signature;
1085 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1086
1087 int N = 1 << ftr->N_factor;
1088 int r = 1 << ftr->r_factor;
1089 int p = 1 << ftr->p_factor;
1090
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001091 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1092 salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001093 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001094
1095 if (rc) {
1096 SLOGE("scrypt failed");
1097 return -1;
1098 }
1099
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001100 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE,
Shawn Willdene17a9c42014-09-08 13:04:08 -06001101 &signature, &signature_size)) {
1102 SLOGE("Signing failed");
1103 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001104 }
1105
1106 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001107 N, r, p, ikey, INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001108 free(signature);
1109
1110 if (rc) {
1111 SLOGE("scrypt failed");
1112 return -1;
1113 }
1114
1115 return 0;
1116}
1117
1118static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1119 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001120 unsigned char *encrypted_master_key,
1121 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001122{
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001123 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = { 0 };
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001124 EVP_CIPHER_CTX e_ctx;
1125 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001126 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001127
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001128 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001129 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001130
1131 switch (crypt_ftr->kdf_type) {
1132 case KDF_SCRYPT_KEYMASTER:
1133 if (keymaster_create_key(crypt_ftr)) {
1134 SLOGE("keymaster_create_key failed");
1135 return -1;
1136 }
1137
1138 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1139 SLOGE("scrypt failed");
1140 return -1;
1141 }
1142 break;
1143
1144 case KDF_SCRYPT:
1145 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1146 SLOGE("scrypt failed");
1147 return -1;
1148 }
1149 break;
1150
1151 default:
1152 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001153 return -1;
1154 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001155
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001156 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001157 EVP_CIPHER_CTX_init(&e_ctx);
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001158 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1159 ikey+INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001160 SLOGE("EVP_EncryptInit failed\n");
1161 return -1;
1162 }
1163 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001164
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001165 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001166 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Greg Kaiserfa099612018-02-14 11:26:00 -08001167 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001168 SLOGE("EVP_EncryptUpdate failed\n");
1169 return -1;
1170 }
Adam Langley889c4f12014-09-03 14:23:13 -07001171 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001172 SLOGE("EVP_EncryptFinal failed\n");
1173 return -1;
1174 }
1175
Greg Kaiserfa099612018-02-14 11:26:00 -08001176 if (encrypted_len + final_len != KEY_LEN_BYTES) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001177 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1178 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001179 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001180
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001181 /* Store the scrypt of the intermediate key, so we can validate if it's a
1182 password error or mount error when things go wrong.
1183 Note there's no need to check for errors, since if this is incorrect, we
1184 simply won't wipe userdata, which is the correct default behavior
1185 */
1186 int N = 1 << crypt_ftr->N_factor;
1187 int r = 1 << crypt_ftr->r_factor;
1188 int p = 1 << crypt_ftr->p_factor;
1189
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001190 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001191 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1192 crypt_ftr->scrypted_intermediate_key,
1193 sizeof(crypt_ftr->scrypted_intermediate_key));
1194
1195 if (rc) {
1196 SLOGE("encrypt_master_key: crypto_scrypt failed");
1197 }
1198
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001199 EVP_CIPHER_CTX_cleanup(&e_ctx);
1200
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001201 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001202}
1203
Paul Lawrence731a7a22015-04-28 22:14:15 +00001204static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001205 unsigned char *encrypted_master_key,
1206 unsigned char *decrypted_master_key,
1207 kdf_func kdf, void *kdf_params,
1208 unsigned char** intermediate_key,
1209 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001210{
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001211 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = { 0 };
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001212 EVP_CIPHER_CTX d_ctx;
1213 int decrypted_len, final_len;
1214
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001215 /* Turn the password into an intermediate key and IV that can decrypt the
1216 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001217 if (kdf(passwd, salt, ikey, kdf_params)) {
1218 SLOGE("kdf failed");
1219 return -1;
1220 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001221
1222 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001223 EVP_CIPHER_CTX_init(&d_ctx);
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001224 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001225 return -1;
1226 }
1227 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1228 /* Decrypt the master key */
1229 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
Greg Kaiserfa099612018-02-14 11:26:00 -08001230 encrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001231 return -1;
1232 }
Adam Langley889c4f12014-09-03 14:23:13 -07001233 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001234 return -1;
1235 }
1236
Greg Kaiserfa099612018-02-14 11:26:00 -08001237 if (decrypted_len + final_len != KEY_LEN_BYTES) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001238 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001239 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001240
1241 /* Copy intermediate key if needed by params */
1242 if (intermediate_key && intermediate_key_size) {
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001243 *intermediate_key = (unsigned char*) malloc(INTERMEDIATE_KEY_LEN_BYTES);
Greg Kaisere8167af2016-04-20 10:50:15 -07001244 if (*intermediate_key) {
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001245 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1246 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001247 }
1248 }
1249
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001250 EVP_CIPHER_CTX_cleanup(&d_ctx);
1251
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001252 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001253}
1254
Kenny Rootc4c70f12013-06-14 12:11:38 -07001255static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001256{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001257 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001258 *kdf = scrypt_keymaster;
1259 *kdf_params = ftr;
1260 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001261 *kdf = scrypt;
1262 *kdf_params = ftr;
1263 } else {
1264 *kdf = pbkdf2;
1265 *kdf_params = NULL;
1266 }
1267}
1268
Paul Lawrence731a7a22015-04-28 22:14:15 +00001269static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001270 struct crypt_mnt_ftr *crypt_ftr,
1271 unsigned char** intermediate_key,
1272 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001273{
1274 kdf_func kdf;
1275 void *kdf_params;
1276 int ret;
1277
1278 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001279 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1280 decrypted_master_key, kdf, kdf_params,
1281 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001282 if (ret != 0) {
1283 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001284 }
1285
1286 return ret;
1287}
1288
Wei Wang4375f1b2017-02-24 17:43:01 -08001289static int create_encrypted_random_key(const char *passwd, unsigned char *master_key, unsigned char *salt,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001290 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001291 int fd;
Greg Kaiserfa099612018-02-14 11:26:00 -08001292 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001293
1294 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001295 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001296 read(fd, key_buf, sizeof(key_buf));
1297 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001298 close(fd);
1299
1300 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001301 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001302}
1303
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001304int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001305{
Greg Hackmann955653e2014-09-24 14:55:20 -07001306 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001307#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001308
1309 /* Now umount the tmpfs filesystem */
1310 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001311 if (umount(mountpoint) == 0) {
1312 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001313 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001314
1315 if (errno == EINVAL) {
1316 /* EINVAL is returned if the directory is not a mountpoint,
1317 * i.e. there is no filesystem mounted there. So just get out.
1318 */
1319 break;
1320 }
1321
1322 err = errno;
1323
1324 /* If allowed, be increasingly aggressive before the last two retries */
1325 if (kill) {
1326 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1327 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001328 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001329 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1330 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001331 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001332 }
1333 }
1334
1335 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001336 }
1337
1338 if (i < WAIT_UNMOUNT_COUNT) {
1339 SLOGD("unmounting %s succeeded\n", mountpoint);
1340 rc = 0;
1341 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001342 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001343 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001344 rc = -1;
1345 }
1346
1347 return rc;
1348}
1349
Wei Wang42e38102017-06-07 10:46:12 -07001350static void prep_data_fs(void)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001351{
Jeff Sharkey47695b22016-02-01 17:02:29 -07001352 // NOTE: post_fs_data results in init calling back around to vold, so all
1353 // callers to this method must be async
1354
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001355 /* Do the prep of the /data filesystem */
1356 property_set("vold.post_fs_data_done", "0");
1357 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001358 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001359
Ken Sumrallc5872692013-05-14 15:26:31 -07001360 /* Wait a max of 50 seconds, hopefully it takes much less */
Wei Wang42e38102017-06-07 10:46:12 -07001361 while (!android::base::WaitForProperty("vold.post_fs_data_done",
Wei Wang4375f1b2017-02-24 17:43:01 -08001362 "1",
Wei Wang42e38102017-06-07 10:46:12 -07001363 std::chrono::seconds(15))) {
1364 /* We timed out to prep /data in time. Continue wait. */
1365 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001366 }
Wei Wang42e38102017-06-07 10:46:12 -07001367 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001368}
1369
Paul Lawrence74f29f12014-08-28 15:54:10 -07001370static void cryptfs_set_corrupt()
1371{
1372 // Mark the footer as bad
1373 struct crypt_mnt_ftr crypt_ftr;
1374 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1375 SLOGE("Failed to get crypto footer - panic");
1376 return;
1377 }
1378
1379 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1380 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1381 SLOGE("Failed to set crypto footer - panic");
1382 return;
1383 }
1384}
1385
1386static void cryptfs_trigger_restart_min_framework()
1387{
1388 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1389 SLOGE("Failed to mount tmpfs on data - panic");
1390 return;
1391 }
1392
1393 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1394 SLOGE("Failed to trigger post fs data - panic");
1395 return;
1396 }
1397
1398 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1399 SLOGE("Failed to trigger restart min framework - panic");
1400 return;
1401 }
1402}
1403
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001404/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001405static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001406{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001407 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001408 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001409 static int restart_successful = 0;
1410
1411 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001412 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001413 SLOGE("Encrypted filesystem not validated, aborting");
1414 return -1;
1415 }
1416
1417 if (restart_successful) {
1418 SLOGE("System already restarted with encrypted disk, aborting");
1419 return -1;
1420 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001421
Paul Lawrencef4faa572014-01-29 13:31:03 -08001422 if (restart_main) {
1423 /* Here is where we shut down the framework. The init scripts
1424 * start all services in one of three classes: core, main or late_start.
1425 * On boot, we start core and main. Now, we stop main, but not core,
1426 * as core includes vold and a few other really important things that
1427 * we need to keep running. Once main has stopped, we should be able
1428 * to umount the tmpfs /data, then mount the encrypted /data.
1429 * We then restart the class main, and also the class late_start.
1430 * At the moment, I've only put a few things in late_start that I know
1431 * are not needed to bring up the framework, and that also cause problems
1432 * with unmounting the tmpfs /data, but I hope to add add more services
1433 * to the late_start class as we optimize this to decrease the delay
1434 * till the user is asked for the password to the filesystem.
1435 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001436
Paul Lawrencef4faa572014-01-29 13:31:03 -08001437 /* The init files are setup to stop the class main when vold.decrypt is
1438 * set to trigger_reset_main.
1439 */
1440 property_set("vold.decrypt", "trigger_reset_main");
1441 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001442
Paul Lawrencef4faa572014-01-29 13:31:03 -08001443 /* Ugh, shutting down the framework is not synchronous, so until it
1444 * can be fixed, this horrible hack will wait a moment for it all to
1445 * shut down before proceeding. Without it, some devices cannot
1446 * restart the graphics services.
1447 */
1448 sleep(2);
1449 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001450
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001451 /* Now that the framework is shutdown, we should be able to umount()
1452 * the tmpfs filesystem, and mount the real one.
1453 */
1454
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001455 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1456 if (strlen(crypto_blkdev) == 0) {
1457 SLOGE("fs_crypto_blkdev not set\n");
1458 return -1;
1459 }
1460
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001461 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001462 /* If ro.crypto.readonly is set to 1, mount the decrypted
1463 * filesystem readonly. This is used when /data is mounted by
1464 * recovery mode.
1465 */
1466 char ro_prop[PROPERTY_VALUE_MAX];
1467 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001468 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001469 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Doug Zongker6fd57712013-12-17 09:43:23 -08001470 rec->flags |= MS_RDONLY;
1471 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001472
Ken Sumralle5032c42012-04-01 23:58:44 -07001473 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001474 int retries = RETRY_MOUNT_ATTEMPTS;
1475 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001476
1477 /*
1478 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1479 * partitions in the fsck domain.
1480 */
1481 if (setexeccon(secontextFsck())){
1482 SLOGE("Failed to setexeccon");
1483 return -1;
1484 }
Paul Crowleye2ee1522017-09-26 14:05:26 -07001485 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT,
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001486 crypto_blkdev, 0))
1487 != 0) {
1488 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1489 /* TODO: invoke something similar to
1490 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1491 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1492 SLOGI("Failed to mount %s because it is busy - waiting",
1493 crypto_blkdev);
1494 if (--retries) {
1495 sleep(RETRY_MOUNT_DELAY_SECONDS);
1496 } else {
1497 /* Let's hope that a reboot clears away whatever is keeping
1498 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001499 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001500 }
1501 } else {
1502 SLOGE("Failed to mount decrypted data");
1503 cryptfs_set_corrupt();
1504 cryptfs_trigger_restart_min_framework();
1505 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001506 if (setexeccon(NULL)) {
1507 SLOGE("Failed to setexeccon");
1508 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001509 return -1;
1510 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001511 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001512 if (setexeccon(NULL)) {
1513 SLOGE("Failed to setexeccon");
1514 return -1;
1515 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001516
Ken Sumralle5032c42012-04-01 23:58:44 -07001517 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001518 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001519 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001520
1521 /* startup service classes main and late_start */
1522 property_set("vold.decrypt", "trigger_restart_framework");
1523 SLOGD("Just triggered restart_framework\n");
1524
1525 /* Give it a few moments to get started */
1526 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001527 }
1528
Ken Sumrall0cc16632011-01-18 20:32:26 -08001529 if (rc == 0) {
1530 restart_successful = 1;
1531 }
1532
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001533 return rc;
1534}
1535
Paul Lawrencef4faa572014-01-29 13:31:03 -08001536int cryptfs_restart(void)
1537{
Paul Lawrence05335c32015-03-05 09:46:23 -08001538 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001539 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001540 SLOGE("cryptfs_restart not valid for file encryption:");
1541 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001542 }
1543
Paul Lawrencef4faa572014-01-29 13:31:03 -08001544 /* Call internal implementation forcing a restart of main service group */
1545 return cryptfs_restart_internal(1);
1546}
1547
Wei Wang4375f1b2017-02-24 17:43:01 -08001548static int do_crypto_complete(const char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001549{
1550 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001551 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001552 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001553
1554 property_get("ro.crypto.state", encrypted_state, "");
1555 if (strcmp(encrypted_state, "encrypted") ) {
1556 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001557 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001558 }
1559
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001560 // crypto_complete is full disk encrypted status
Paul Crowley38132a12016-02-09 09:50:32 +00001561 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001562 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Paul Lawrence05335c32015-03-05 09:46:23 -08001563 }
1564
Ken Sumrall160b4d62013-04-22 12:15:39 -07001565 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001566 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001567
Ken Sumralle1a45852011-12-14 21:24:27 -08001568 /*
1569 * Only report this error if key_loc is a file and it exists.
1570 * If the device was never encrypted, and /data is not mountable for
1571 * some reason, returning 1 should prevent the UI from presenting the
1572 * a "enter password" screen, or worse, a "press button to wipe the
1573 * device" screen.
1574 */
1575 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1576 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001577 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001578 } else {
1579 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001580 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001581 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001582 }
1583
Paul Lawrence74f29f12014-08-28 15:54:10 -07001584 // Test for possible error flags
1585 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1586 SLOGE("Encryption process is partway completed\n");
1587 return CRYPTO_COMPLETE_PARTIAL;
1588 }
1589
1590 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1591 SLOGE("Encryption process was interrupted but cannot continue\n");
1592 return CRYPTO_COMPLETE_INCONSISTENT;
1593 }
1594
1595 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1596 SLOGE("Encryption is successful but data is corrupt\n");
1597 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001598 }
1599
1600 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001601 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001602}
1603
Paul Lawrencef4faa572014-01-29 13:31:03 -08001604static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
Wei Wang4375f1b2017-02-24 17:43:01 -08001605 const char *passwd, const char *mount_point, const char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001606{
Greg Kaiser00eda382018-02-14 20:15:18 -08001607 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001608 char crypto_blkdev[MAXPATHLEN];
1609 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001610 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001611 unsigned int orig_failed_decrypt_count;
1612 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001613 int use_keymaster = 0;
1614 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001615 unsigned char* intermediate_key = 0;
1616 size_t intermediate_key_size = 0;
Wei Wang4375f1b2017-02-24 17:43:01 -08001617 int N = 1 << crypt_ftr->N_factor;
1618 int r = 1 << crypt_ftr->r_factor;
1619 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001620
Paul Lawrencef4faa572014-01-29 13:31:03 -08001621 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1622 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001623
Paul Lawrencef4faa572014-01-29 13:31:03 -08001624 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001625 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1626 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001627 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001628 rc = -1;
1629 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001630 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001631 }
1632
Paul Crowleye2ee1522017-09-26 14:05:26 -07001633 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Paul Lawrencef4faa572014-01-29 13:31:03 -08001634
Paul Lawrence74f29f12014-08-28 15:54:10 -07001635 // Create crypto block device - all (non fatal) code paths
1636 // need it
Paul Crowley5afbc622017-11-27 09:42:17 -08001637 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label, 0)) {
1638 SLOGE("Error creating decrypted block device\n");
1639 rc = -1;
1640 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001641 }
1642
Paul Lawrence74f29f12014-08-28 15:54:10 -07001643 /* Work out if the problem is the password or the data */
1644 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1645 scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001646
Paul Lawrence74f29f12014-08-28 15:54:10 -07001647 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1648 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1649 N, r, p, scrypted_intermediate_key,
1650 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001651
Paul Lawrence74f29f12014-08-28 15:54:10 -07001652 // Does the key match the crypto footer?
1653 if (rc == 0 && memcmp(scrypted_intermediate_key,
1654 crypt_ftr->scrypted_intermediate_key,
1655 sizeof(scrypted_intermediate_key)) == 0) {
1656 SLOGI("Password matches");
1657 rc = 0;
1658 } else {
1659 /* Try mounting the file system anyway, just in case the problem's with
1660 * the footer, not the key. */
George Burgess IV605d7ae2016-02-29 13:39:17 -08001661 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt",
1662 mount_point);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001663 mkdir(tmp_mount_point, 0755);
Paul Crowleye2ee1522017-09-26 14:05:26 -07001664 if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001665 SLOGE("Error temp mounting decrypted block device\n");
1666 delete_crypto_blk_dev(label);
1667
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001668 rc = ++crypt_ftr->failed_decrypt_count;
1669 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001670 } else {
1671 /* Success! */
1672 SLOGI("Password did not match but decrypted drive mounted - continue");
1673 umount(tmp_mount_point);
1674 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001675 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001676 }
1677
1678 if (rc == 0) {
1679 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001680 if (orig_failed_decrypt_count != 0) {
1681 put_crypt_ftr_and_key(crypt_ftr);
1682 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001683
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001684 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001685 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001686 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001687
1688 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001689 * the key when we want to change the password on it. */
Greg Kaiserfa099612018-02-14 11:26:00 -08001690 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001691 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001692 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001693 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001694 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001695
Paul Lawrence74f29f12014-08-28 15:54:10 -07001696 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001697 use_keymaster = keymaster_check_compatibility();
1698 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001699 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001700 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1701 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1702 upgrade = 1;
1703 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001704 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001705 upgrade = 1;
1706 }
1707
1708 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001709 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1710 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001711 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001712 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001713 }
1714 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001715
1716 // Do not fail even if upgrade failed - machine is bootable
1717 // Note that if this code is ever hit, there is a *serious* problem
1718 // since KDFs should never fail. You *must* fix the kdf before
1719 // proceeding!
1720 if (rc) {
1721 SLOGW("Upgrade failed with error %d,"
1722 " but continuing with previous state",
1723 rc);
1724 rc = 0;
1725 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001726 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001727 }
1728
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001729 errout:
1730 if (intermediate_key) {
1731 memset(intermediate_key, 0, intermediate_key_size);
1732 free(intermediate_key);
1733 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001734 return rc;
1735}
1736
Ken Sumrall29d8da82011-05-18 17:20:07 -07001737/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001738 * Called by vold when it's asked to mount an encrypted external
1739 * storage volume. The incoming partition has no crypto header/footer,
1740 * as any metadata is been stored in a separate, small partition.
1741 *
1742 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001743 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001744int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1745 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001746 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001747 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001748 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001749 return -1;
1750 }
1751
1752 unsigned long nr_sec = 0;
1753 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001754 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001755
Ken Sumrall29d8da82011-05-18 17:20:07 -07001756 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001757 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001758 return -1;
1759 }
1760
Jeff Sharkey9c484982015-03-31 10:35:33 -07001761 struct crypt_mnt_ftr ext_crypt_ftr;
1762 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1763 ext_crypt_ftr.fs_size = nr_sec;
1764 ext_crypt_ftr.keysize = keysize;
Greg Kaiserfa099612018-02-14 11:26:00 -08001765 strlcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256",
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001766 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001767
Paul Crowley5afbc622017-11-27 09:42:17 -08001768 return create_crypto_blk_dev(
1769 &ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label,
1770 e4crypt_is_native() ? CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE : 0);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001771}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001772
Jeff Sharkey9c484982015-03-31 10:35:33 -07001773/*
1774 * Called by vold when it's asked to unmount an encrypted external
1775 * storage volume.
1776 */
1777int cryptfs_revert_ext_volume(const char* label) {
1778 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001779}
1780
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001781int cryptfs_crypto_complete(void)
1782{
1783 return do_crypto_complete("/data");
1784}
1785
Paul Lawrencef4faa572014-01-29 13:31:03 -08001786int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1787{
1788 char encrypted_state[PROPERTY_VALUE_MAX];
1789 property_get("ro.crypto.state", encrypted_state, "");
1790 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1791 SLOGE("encrypted fs already validated or not running with encryption,"
1792 " aborting");
1793 return -1;
1794 }
1795
1796 if (get_crypt_ftr_and_key(crypt_ftr)) {
1797 SLOGE("Error getting crypt footer and key");
1798 return -1;
1799 }
1800
1801 return 0;
1802}
1803
Wei Wang4375f1b2017-02-24 17:43:01 -08001804int cryptfs_check_passwd(const char *passwd)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001805{
Paul Lawrence05335c32015-03-05 09:46:23 -08001806 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00001807 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001808 SLOGE("cryptfs_check_passwd not valid for file encryption");
1809 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001810 }
1811
Paul Lawrencef4faa572014-01-29 13:31:03 -08001812 struct crypt_mnt_ftr crypt_ftr;
1813 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001814
Paul Lawrencef4faa572014-01-29 13:31:03 -08001815 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001816 if (rc) {
1817 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001818 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001819 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001820
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001821 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001822 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1823 if (rc) {
1824 SLOGE("Password did not match");
1825 return rc;
1826 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001827
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001828 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1829 // Here we have a default actual password but a real password
1830 // we must test against the scrypted value
1831 // First, we must delete the crypto block device that
1832 // test_mount_encrypted_fs leaves behind as a side effect
1833 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
1834 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
1835 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1836 if (rc) {
1837 SLOGE("Default password did not match on reboot encryption");
1838 return rc;
1839 }
1840
1841 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1842 put_crypt_ftr_and_key(&crypt_ftr);
1843 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1844 if (rc) {
1845 SLOGE("Could not change password on reboot encryption");
1846 return rc;
1847 }
1848 }
1849
1850 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001851 cryptfs_clear_password();
1852 password = strdup(passwd);
1853 struct timespec now;
1854 clock_gettime(CLOCK_BOOTTIME, &now);
1855 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001856 }
1857
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001858 return rc;
1859}
1860
Jeff Sharkey83b559c2017-09-12 16:30:52 -06001861int cryptfs_verify_passwd(const char *passwd)
Ken Sumrall3ad90722011-10-04 20:38:29 -07001862{
1863 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser00eda382018-02-14 20:15:18 -08001864 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001865 char encrypted_state[PROPERTY_VALUE_MAX];
1866 int rc;
1867
1868 property_get("ro.crypto.state", encrypted_state, "");
1869 if (strcmp(encrypted_state, "encrypted") ) {
1870 SLOGE("device not encrypted, aborting");
1871 return -2;
1872 }
1873
1874 if (!master_key_saved) {
1875 SLOGE("encrypted fs not yet mounted, aborting");
1876 return -1;
1877 }
1878
1879 if (!saved_mount_point) {
1880 SLOGE("encrypted fs failed to save mount point, aborting");
1881 return -1;
1882 }
1883
Ken Sumrall160b4d62013-04-22 12:15:39 -07001884 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001885 SLOGE("Error getting crypt footer and key\n");
1886 return -1;
1887 }
1888
1889 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1890 /* If the device has no password, then just say the password is valid */
1891 rc = 0;
1892 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001893 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001894 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1895 /* They match, the password is correct */
1896 rc = 0;
1897 } else {
1898 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1899 sleep(1);
1900 rc = 1;
1901 }
1902 }
1903
1904 return rc;
1905}
1906
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001907/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiserfa099612018-02-14 11:26:00 -08001908 * defaulted to 16 bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001909 * Presumably, at a minimum, the caller will update the
1910 * filesystem size and crypto_type_name after calling this function.
1911 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001912static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001913{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001914 off64_t off;
1915
1916 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001917 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001918 ftr->major_version = CURRENT_MAJOR_VERSION;
1919 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001920 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiserfa099612018-02-14 11:26:00 -08001921 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001922
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001923 switch (keymaster_check_compatibility()) {
1924 case 1:
1925 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1926 break;
1927
1928 case 0:
1929 ftr->kdf_type = KDF_SCRYPT;
1930 break;
1931
1932 default:
1933 SLOGE("keymaster_check_compatibility failed");
1934 return -1;
1935 }
1936
Kenny Rootc4c70f12013-06-14 12:11:38 -07001937 get_device_scrypt_params(ftr);
1938
Ken Sumrall160b4d62013-04-22 12:15:39 -07001939 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1940 if (get_crypt_ftr_info(NULL, &off) == 0) {
1941 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1942 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1943 ftr->persist_data_size;
1944 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001945
1946 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001947}
1948
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001949#define FRAMEWORK_BOOT_WAIT 60
1950
Paul Lawrence87999172014-02-20 12:21:31 -08001951static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
1952{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001953 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08001954 if (fd == -1) {
1955 SLOGE("Error opening file %s", filename);
1956 return -1;
1957 }
1958
1959 char block[CRYPT_INPLACE_BUFSIZE];
1960 memset(block, 0, sizeof(block));
1961 if (unix_read(fd, block, sizeof(block)) < 0) {
1962 SLOGE("Error reading file %s", filename);
1963 close(fd);
1964 return -1;
1965 }
1966
1967 close(fd);
1968
1969 SHA256_CTX c;
1970 SHA256_Init(&c);
1971 SHA256_Update(&c, block, sizeof(block));
1972 SHA256_Final(buf, &c);
1973
1974 return 0;
1975}
1976
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001977static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
1978 char* real_blkdev, int previously_encrypted_upto) {
Paul Lawrence87999172014-02-20 12:21:31 -08001979 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08001980 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08001981
Paul Lawrence87999172014-02-20 12:21:31 -08001982 /* The size of the userdata partition, and add in the vold volumes below */
1983 tot_encryption_size = crypt_ftr->fs_size;
1984
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001985 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08001986 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08001987
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001988 if (rc == ENABLE_INPLACE_ERR_DEV) {
1989 /* Hack for b/17898962 */
1990 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
1991 cryptfs_reboot(RebootType::reboot);
1992 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07001993
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001994 if (!rc) {
1995 crypt_ftr->encrypted_upto = cur_encryption_done;
1996 }
Paul Lawrence87999172014-02-20 12:21:31 -08001997
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001998 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
1999 /* The inplace routine never actually sets the progress to 100% due
2000 * to the round down nature of integer division, so set it here */
2001 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002002 }
2003
2004 return rc;
2005}
2006
Paul Crowleyb64933a2017-10-31 08:25:55 -07002007static int vold_unmountAll(void) {
2008 VolumeManager* vm = VolumeManager::Instance();
2009 return vm->unmountAll();
2010}
2011
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002012int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Lawrence87999172014-02-20 12:21:31 -08002013 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Greg Kaiser2c92d7b2018-02-14 11:26:08 -08002014 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002015 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002016 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002017 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002018 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002019 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002020 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002021 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002022 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002023 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002024 bool onlyCreateHeader = false;
2025 int fd = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002026
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002027 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002028 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2029 /* An encryption was underway and was interrupted */
2030 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2031 crypt_ftr.encrypted_upto = 0;
2032 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002033
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002034 /* At this point, we are in an inconsistent state. Until we successfully
2035 complete encryption, a reboot will leave us broken. So mark the
2036 encryption failed in case that happens.
2037 On successfully completing encryption, remove this flag */
2038 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002039
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002040 put_crypt_ftr_and_key(&crypt_ftr);
2041 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2042 if (!check_ftr_sha(&crypt_ftr)) {
2043 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2044 put_crypt_ftr_and_key(&crypt_ftr);
2045 goto error_unencrypted;
2046 }
2047
2048 /* Doing a reboot-encryption*/
2049 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2050 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2051 rebootEncryption = true;
2052 }
Paul Lawrence87999172014-02-20 12:21:31 -08002053 }
2054
2055 property_get("ro.crypto.state", encrypted_state, "");
2056 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2057 SLOGE("Device is already running encrypted, aborting");
2058 goto error_unencrypted;
2059 }
2060
2061 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002062 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2063 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002064
Ken Sumrall3ed82362011-01-28 23:31:16 -08002065 /* Get the size of the real block device */
Wei Wang4375f1b2017-02-24 17:43:01 -08002066 fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002067 if (fd == -1) {
2068 SLOGE("Cannot open block device %s\n", real_blkdev);
2069 goto error_unencrypted;
2070 }
2071 unsigned long nr_sec;
2072 get_blkdev_size(fd, &nr_sec);
2073 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002074 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2075 goto error_unencrypted;
2076 }
2077 close(fd);
2078
2079 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002080 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002081 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002082 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002083 if (fs_size_sec == 0)
2084 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2085
Paul Lawrence87999172014-02-20 12:21:31 -08002086 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002087
2088 if (fs_size_sec > max_fs_size_sec) {
2089 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2090 goto error_unencrypted;
2091 }
2092 }
2093
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002094 /* Get a wakelock as this may take a while, and we don't want the
2095 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2096 * wants to keep the screen on, it can grab a full wakelock.
2097 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002098 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002099 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2100
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002101 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002102 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002103 */
2104 property_set("vold.decrypt", "trigger_shutdown_framework");
2105 SLOGD("Just asked init to shut down class main\n");
2106
Jeff Sharkey9c484982015-03-31 10:35:33 -07002107 /* Ask vold to unmount all devices that it manages */
2108 if (vold_unmountAll()) {
2109 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002110 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002111
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002112 /* no_ui means we are being called from init, not settings.
2113 Now we always reboot from settings, so !no_ui means reboot
2114 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002115 if (!no_ui) {
2116 /* Try fallback, which is to reboot and try there */
2117 onlyCreateHeader = true;
2118 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2119 if (breadcrumb == 0) {
2120 SLOGE("Failed to create breadcrumb file");
2121 goto error_shutting_down;
2122 }
2123 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002124 }
2125
2126 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002127 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002128 /* Now that /data is unmounted, we need to mount a tmpfs
2129 * /data, set a property saying we're doing inplace encryption,
2130 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002131 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002132 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002133 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002134 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002135 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002136 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002137
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002138 /* restart the framework. */
2139 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002140 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002141
Ken Sumrall92736ef2012-10-17 20:57:14 -07002142 /* Ugh, shutting down the framework is not synchronous, so until it
2143 * can be fixed, this horrible hack will wait a moment for it all to
2144 * shut down before proceeding. Without it, some devices cannot
2145 * restart the graphics services.
2146 */
2147 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002148 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002149
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002150 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002151 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002152 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002153 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2154 goto error_shutting_down;
2155 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002156
Paul Lawrence87999172014-02-20 12:21:31 -08002157 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2158 crypt_ftr.fs_size = nr_sec
2159 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2160 } else {
2161 crypt_ftr.fs_size = nr_sec;
2162 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002163 /* At this point, we are in an inconsistent state. Until we successfully
2164 complete encryption, a reboot will leave us broken. So mark the
2165 encryption failed in case that happens.
2166 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002167 if (onlyCreateHeader) {
2168 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2169 } else {
2170 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2171 }
Paul Lawrence87999172014-02-20 12:21:31 -08002172 crypt_ftr.crypt_type = crypt_type;
Greg Kaiserfa099612018-02-14 11:26:00 -08002173 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002174
Paul Lawrence87999172014-02-20 12:21:31 -08002175 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002176 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2177 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002178 SLOGE("Cannot create encrypted master key\n");
2179 goto error_shutting_down;
2180 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002181
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002182 /* Replace scrypted intermediate key if we are preparing for a reboot */
2183 if (onlyCreateHeader) {
Greg Kaiserfa099612018-02-14 11:26:00 -08002184 unsigned char fake_master_key[KEY_LEN_BYTES];
2185 unsigned char encrypted_fake_master_key[KEY_LEN_BYTES];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002186 memset(fake_master_key, 0, sizeof(fake_master_key));
2187 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
2188 encrypted_fake_master_key, &crypt_ftr);
2189 }
2190
Paul Lawrence87999172014-02-20 12:21:31 -08002191 /* Write the key to the end of the partition */
2192 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002193
Paul Lawrence87999172014-02-20 12:21:31 -08002194 /* If any persistent data has been remembered, save it.
2195 * If none, create a valid empty table and save that.
2196 */
2197 if (!persist_data) {
Wei Wang4375f1b2017-02-24 17:43:01 -08002198 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002199 if (pdata) {
2200 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2201 persist_data = pdata;
2202 }
2203 }
2204 if (persist_data) {
2205 save_persistent_data();
2206 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002207 }
2208
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002209 if (onlyCreateHeader) {
2210 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002211 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002212 }
2213
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002214 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002215 /* startup service classes main and late_start */
2216 property_set("vold.decrypt", "trigger_restart_min_framework");
2217 SLOGD("Just triggered restart_min_framework\n");
2218
2219 /* OK, the framework is restarted and will soon be showing a
2220 * progress bar. Time to setup an encrypted mapping, and
2221 * either write a new filesystem, or encrypt in place updating
2222 * the progress bar as we work.
2223 */
2224 }
2225
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002226 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002227 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002228 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002229
Paul Lawrence87999172014-02-20 12:21:31 -08002230 /* If we are continuing, check checksums match */
2231 rc = 0;
2232 if (previously_encrypted_upto) {
2233 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2234 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002235
Paul Lawrence87999172014-02-20 12:21:31 -08002236 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2237 sizeof(hash_first_block)) != 0) {
2238 SLOGE("Checksums do not match - trigger wipe");
2239 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002240 }
2241 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002242
Paul Lawrence87999172014-02-20 12:21:31 -08002243 if (!rc) {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002244 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002245 previously_encrypted_upto);
2246 }
2247
2248 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002249 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002250 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2251 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002252 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002253 SLOGE("Error calculating checksum for continuing encryption");
2254 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002255 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002256 }
2257
2258 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002259 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002260
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002261 if (! rc) {
2262 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002263 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002264
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002265 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002266 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2267 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002268 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002269 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002270
Paul Lawrence6bfed202014-07-28 12:47:22 -07002271 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002272
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002273 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2274 char value[PROPERTY_VALUE_MAX];
2275 property_get("ro.crypto.state", value, "");
2276 if (!strcmp(value, "")) {
2277 /* default encryption - continue first boot sequence */
2278 property_set("ro.crypto.state", "encrypted");
2279 property_set("ro.crypto.type", "block");
2280 release_wake_lock(lockid);
2281 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2282 // Bring up cryptkeeper that will check the password and set it
2283 property_set("vold.decrypt", "trigger_shutdown_framework");
2284 sleep(2);
2285 property_set("vold.encrypt_progress", "");
2286 cryptfs_trigger_restart_min_framework();
2287 } else {
2288 cryptfs_check_passwd(DEFAULT_PASSWORD);
2289 cryptfs_restart_internal(1);
2290 }
2291 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002292 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002293 sleep(2); /* Give the UI a chance to show 100% progress */
2294 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002295 }
Paul Lawrence87999172014-02-20 12:21:31 -08002296 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002297 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002298 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002299 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002300 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002301 char value[PROPERTY_VALUE_MAX];
2302
Ken Sumrall319369a2012-06-27 16:30:18 -07002303 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002304 if (!strcmp(value, "1")) {
2305 /* wipe data if encryption failed */
2306 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002307 std::string err;
2308 const std::vector<std::string> options = {
2309 "--wipe_data\n--reason=cryptfs_enable_internal\n"
2310 };
2311 if (!write_bootloader_message(options, &err)) {
2312 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002313 }
Josh Gaofec44372017-08-28 13:22:55 -07002314 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002315 } else {
2316 /* set property to trigger dialog */
2317 property_set("vold.encrypt_progress", "error_partially_encrypted");
2318 release_wake_lock(lockid);
2319 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002320 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002321 }
2322
Ken Sumrall3ed82362011-01-28 23:31:16 -08002323 /* hrm, the encrypt step claims success, but the reboot failed.
2324 * This should not happen.
2325 * Set the property and return. Hope the framework can deal with it.
2326 */
2327 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002328 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002329 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002330
2331error_unencrypted:
2332 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002333 if (lockid[0]) {
2334 release_wake_lock(lockid);
2335 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002336 return -1;
2337
2338error_shutting_down:
2339 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2340 * but the framework is stopped and not restarted to show the error, so it's up to
2341 * vold to restart the system.
2342 */
2343 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Josh Gaofec44372017-08-28 13:22:55 -07002344 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002345
2346 /* shouldn't get here */
2347 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002348 if (lockid[0]) {
2349 release_wake_lock(lockid);
2350 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002351 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002352}
2353
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002354int cryptfs_enable(int type, const char* passwd, int no_ui) {
2355 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002356}
2357
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002358int cryptfs_enable_default(int no_ui) {
2359 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002360}
2361
2362int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002363{
Paul Crowley38132a12016-02-09 09:50:32 +00002364 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002365 SLOGE("cryptfs_changepw not valid for file encryption");
2366 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002367 }
2368
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002369 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002370 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002371
2372 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002373 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002374 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002375 return -1;
2376 }
2377
Paul Lawrencef4faa572014-01-29 13:31:03 -08002378 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2379 SLOGE("Invalid crypt_type %d", crypt_type);
2380 return -1;
2381 }
2382
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002383 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002384 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002385 SLOGE("Error getting crypt footer and key");
2386 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002387 }
2388
Paul Lawrencef4faa572014-01-29 13:31:03 -08002389 crypt_ftr.crypt_type = crypt_type;
2390
JP Abgrall933216c2015-02-11 13:44:32 -08002391 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08002392 : newpw,
2393 crypt_ftr.salt,
2394 saved_master_key,
2395 crypt_ftr.master_key,
2396 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002397 if (rc) {
2398 SLOGE("Encrypt master key failed: %d", rc);
2399 return -1;
2400 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002401 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002402 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002403
2404 return 0;
2405}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002406
Rubin Xu85c01f92014-10-13 12:49:54 +01002407static unsigned int persist_get_max_entries(int encrypted) {
2408 struct crypt_mnt_ftr crypt_ftr;
2409 unsigned int dsize;
2410 unsigned int max_persistent_entries;
2411
2412 /* If encrypted, use the values from the crypt_ftr, otherwise
2413 * use the values for the current spec.
2414 */
2415 if (encrypted) {
2416 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2417 return -1;
2418 }
2419 dsize = crypt_ftr.persist_data_size;
2420 } else {
2421 dsize = CRYPT_PERSIST_DATA_SIZE;
2422 }
2423
2424 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2425 sizeof(struct crypt_persist_entry);
2426
2427 return max_persistent_entries;
2428}
2429
2430static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002431{
2432 unsigned int i;
2433
2434 if (persist_data == NULL) {
2435 return -1;
2436 }
2437 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2438 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2439 /* We found it! */
2440 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2441 return 0;
2442 }
2443 }
2444
2445 return -1;
2446}
2447
Rubin Xu85c01f92014-10-13 12:49:54 +01002448static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002449{
2450 unsigned int i;
2451 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002452 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002453
2454 if (persist_data == NULL) {
2455 return -1;
2456 }
2457
Rubin Xu85c01f92014-10-13 12:49:54 +01002458 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002459
2460 num = persist_data->persist_valid_entries;
2461
2462 for (i = 0; i < num; i++) {
2463 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2464 /* We found an existing entry, update it! */
2465 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2466 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2467 return 0;
2468 }
2469 }
2470
2471 /* We didn't find it, add it to the end, if there is room */
2472 if (persist_data->persist_valid_entries < max_persistent_entries) {
2473 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2474 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2475 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2476 persist_data->persist_valid_entries++;
2477 return 0;
2478 }
2479
2480 return -1;
2481}
2482
Rubin Xu85c01f92014-10-13 12:49:54 +01002483/**
2484 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2485 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2486 */
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002487int match_multi_entry(const char *key, const char *field, unsigned index) {
2488 std::string key_ = key;
2489 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002490
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002491 std::string parsed_field;
2492 unsigned parsed_index;
2493
2494 std::string::size_type split = key_.find_last_of('_');
2495 if (split == std::string::npos) {
2496 parsed_field = key_;
2497 parsed_index = 0;
2498 } else {
2499 parsed_field = key_.substr(0, split);
2500 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002501 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002502
2503 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002504}
2505
2506/*
2507 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2508 * remaining entries starting from index will be deleted.
2509 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2510 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2511 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2512 *
2513 */
2514static int persist_del_keys(const char *fieldname, unsigned index)
2515{
2516 unsigned int i;
2517 unsigned int j;
2518 unsigned int num;
2519
2520 if (persist_data == NULL) {
2521 return PERSIST_DEL_KEY_ERROR_OTHER;
2522 }
2523
2524 num = persist_data->persist_valid_entries;
2525
2526 j = 0; // points to the end of non-deleted entries.
2527 // Filter out to-be-deleted entries in place.
2528 for (i = 0; i < num; i++) {
2529 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2530 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2531 j++;
2532 }
2533 }
2534
2535 if (j < num) {
2536 persist_data->persist_valid_entries = j;
2537 // Zeroise the remaining entries
2538 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2539 return PERSIST_DEL_KEY_OK;
2540 } else {
2541 // Did not find an entry matching the given fieldname
2542 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2543 }
2544}
2545
2546static int persist_count_keys(const char *fieldname)
2547{
2548 unsigned int i;
2549 unsigned int count;
2550
2551 if (persist_data == NULL) {
2552 return -1;
2553 }
2554
2555 count = 0;
2556 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2557 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2558 count++;
2559 }
2560 }
2561
2562 return count;
2563}
2564
Ken Sumrall160b4d62013-04-22 12:15:39 -07002565/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002566int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002567{
Paul Crowley38132a12016-02-09 09:50:32 +00002568 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002569 SLOGE("Cannot get field when file encrypted");
2570 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002571 }
2572
Ken Sumrall160b4d62013-04-22 12:15:39 -07002573 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002574 /* CRYPTO_GETFIELD_OK is success,
2575 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2576 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2577 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002578 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002579 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2580 int i;
2581 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002582
2583 if (persist_data == NULL) {
2584 load_persistent_data();
2585 if (persist_data == NULL) {
2586 SLOGE("Getfield error, cannot load persistent data");
2587 goto out;
2588 }
2589 }
2590
Rubin Xu85c01f92014-10-13 12:49:54 +01002591 // Read value from persistent entries. If the original value is split into multiple entries,
2592 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002593 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002594 // We found it, copy it to the caller's buffer and keep going until all entries are read.
2595 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
2596 // value too small
2597 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2598 goto out;
2599 }
2600 rc = CRYPTO_GETFIELD_OK;
2601
2602 for (i = 1; /* break explicitly */; i++) {
2603 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
2604 (int) sizeof(temp_field)) {
2605 // If the fieldname is very long, we stop as soon as it begins to overflow the
2606 // maximum field length. At this point we have in fact fully read out the original
2607 // value because cryptfs_setfield would not allow fields with longer names to be
2608 // written in the first place.
2609 break;
2610 }
2611 if (!persist_get_key(temp_field, temp_value)) {
2612 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2613 // value too small.
2614 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2615 goto out;
2616 }
2617 } else {
2618 // Exhaust all entries.
2619 break;
2620 }
2621 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002622 } else {
2623 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002624 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002625 }
2626
2627out:
2628 return rc;
2629}
2630
2631/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002632int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002633{
Paul Crowley38132a12016-02-09 09:50:32 +00002634 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002635 SLOGE("Cannot set field when file encrypted");
2636 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002637 }
2638
Ken Sumrall160b4d62013-04-22 12:15:39 -07002639 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002640 /* 0 is success, negative values are error */
2641 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002642 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002643 unsigned int field_id;
2644 char temp_field[PROPERTY_KEY_MAX];
2645 unsigned int num_entries;
2646 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002647
2648 if (persist_data == NULL) {
2649 load_persistent_data();
2650 if (persist_data == NULL) {
2651 SLOGE("Setfield error, cannot load persistent data");
2652 goto out;
2653 }
2654 }
2655
2656 property_get("ro.crypto.state", encrypted_state, "");
2657 if (!strcmp(encrypted_state, "encrypted") ) {
2658 encrypted = 1;
2659 }
2660
Rubin Xu85c01f92014-10-13 12:49:54 +01002661 // Compute the number of entries required to store value, each entry can store up to
2662 // (PROPERTY_VALUE_MAX - 1) chars
2663 if (strlen(value) == 0) {
2664 // Empty value also needs one entry to store.
2665 num_entries = 1;
2666 } else {
2667 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2668 }
2669
2670 max_keylen = strlen(fieldname);
2671 if (num_entries > 1) {
2672 // Need an extra "_%d" suffix.
2673 max_keylen += 1 + log10(num_entries);
2674 }
2675 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2676 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002677 goto out;
2678 }
2679
Rubin Xu85c01f92014-10-13 12:49:54 +01002680 // Make sure we have enough space to write the new value
2681 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2682 persist_get_max_entries(encrypted)) {
2683 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2684 goto out;
2685 }
2686
2687 // Now that we know persist_data has enough space for value, let's delete the old field first
2688 // to make up space.
2689 persist_del_keys(fieldname, 0);
2690
2691 if (persist_set_key(fieldname, value, encrypted)) {
2692 // fail to set key, should not happen as we have already checked the available space
2693 SLOGE("persist_set_key() error during setfield()");
2694 goto out;
2695 }
2696
2697 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002698 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002699
2700 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2701 // fail to set key, should not happen as we have already checked the available space.
2702 SLOGE("persist_set_key() error during setfield()");
2703 goto out;
2704 }
2705 }
2706
Ken Sumrall160b4d62013-04-22 12:15:39 -07002707 /* If we are running encrypted, save the persistent data now */
2708 if (encrypted) {
2709 if (save_persistent_data()) {
2710 SLOGE("Setfield error, cannot save persistent data");
2711 goto out;
2712 }
2713 }
2714
Rubin Xu85c01f92014-10-13 12:49:54 +01002715 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002716
2717out:
2718 return rc;
2719}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002720
2721/* Checks userdata. Attempt to mount the volume if default-
2722 * encrypted.
2723 * On success trigger next init phase and return 0.
2724 * Currently do not handle failure - see TODO below.
2725 */
2726int cryptfs_mount_default_encrypted(void)
2727{
Paul Lawrence84274cc2016-04-15 15:41:33 -07002728 int crypt_type = cryptfs_get_password_type();
2729 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2730 SLOGE("Bad crypt type - error");
2731 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2732 SLOGD("Password is not default - "
2733 "starting min framework to prompt");
2734 property_set("vold.decrypt", "trigger_restart_min_framework");
2735 return 0;
2736 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2737 SLOGD("Password is default - restarting filesystem");
2738 cryptfs_restart_internal(0);
2739 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002740 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002741 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002742 }
2743
Paul Lawrence6bfed202014-07-28 12:47:22 -07002744 /** Corrupt. Allow us to boot into framework, which will detect bad
2745 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002746 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002747 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002748 return 0;
2749}
2750
2751/* Returns type of the password, default, pattern, pin or password.
2752 */
2753int cryptfs_get_password_type(void)
2754{
Paul Crowley38132a12016-02-09 09:50:32 +00002755 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002756 SLOGE("cryptfs_get_password_type not valid for file encryption");
2757 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002758 }
2759
Paul Lawrencef4faa572014-01-29 13:31:03 -08002760 struct crypt_mnt_ftr crypt_ftr;
2761
2762 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2763 SLOGE("Error getting crypt footer and key\n");
2764 return -1;
2765 }
2766
Paul Lawrence6bfed202014-07-28 12:47:22 -07002767 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2768 return -1;
2769 }
2770
Paul Lawrencef4faa572014-01-29 13:31:03 -08002771 return crypt_ftr.crypt_type;
2772}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002773
Paul Lawrence05335c32015-03-05 09:46:23 -08002774const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002775{
Paul Crowley38132a12016-02-09 09:50:32 +00002776 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002777 SLOGE("cryptfs_get_password not valid for file encryption");
2778 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002779 }
2780
Paul Lawrence399317e2014-03-10 13:20:50 -07002781 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002782 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002783 if (now.tv_sec < password_expiry_time) {
2784 return password;
2785 } else {
2786 cryptfs_clear_password();
2787 return 0;
2788 }
2789}
2790
2791void cryptfs_clear_password()
2792{
2793 if (password) {
2794 size_t len = strlen(password);
2795 memset(password, 0, len);
2796 free(password);
2797 password = 0;
2798 password_expiry_time = 0;
2799 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002800}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002801
Paul Lawrence0c247462015-10-29 10:30:57 -07002802int cryptfs_isConvertibleToFBE()
2803{
Paul Crowleye2ee1522017-09-26 14:05:26 -07002804 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Paul Lawrence0c247462015-10-29 10:30:57 -07002805 return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
2806}