blob: f32bb423468728c944daadfc137748af0f6c61a2 [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 Kaiser2c92d7b2018-02-14 11:26:08 -08001607 /* Allocate enough space for a 256 bit key, but we may use less */
1608 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001609 char crypto_blkdev[MAXPATHLEN];
1610 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001611 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001612 unsigned int orig_failed_decrypt_count;
1613 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001614 int use_keymaster = 0;
1615 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001616 unsigned char* intermediate_key = 0;
1617 size_t intermediate_key_size = 0;
Wei Wang4375f1b2017-02-24 17:43:01 -08001618 int N = 1 << crypt_ftr->N_factor;
1619 int r = 1 << crypt_ftr->r_factor;
1620 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001621
Paul Lawrencef4faa572014-01-29 13:31:03 -08001622 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1623 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001624
Paul Lawrencef4faa572014-01-29 13:31:03 -08001625 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001626 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1627 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001628 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001629 rc = -1;
1630 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001631 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001632 }
1633
Paul Crowleye2ee1522017-09-26 14:05:26 -07001634 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Paul Lawrencef4faa572014-01-29 13:31:03 -08001635
Paul Lawrence74f29f12014-08-28 15:54:10 -07001636 // Create crypto block device - all (non fatal) code paths
1637 // need it
Paul Crowley5afbc622017-11-27 09:42:17 -08001638 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label, 0)) {
1639 SLOGE("Error creating decrypted block device\n");
1640 rc = -1;
1641 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001642 }
1643
Paul Lawrence74f29f12014-08-28 15:54:10 -07001644 /* Work out if the problem is the password or the data */
1645 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1646 scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001647
Paul Lawrence74f29f12014-08-28 15:54:10 -07001648 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1649 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1650 N, r, p, scrypted_intermediate_key,
1651 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001652
Paul Lawrence74f29f12014-08-28 15:54:10 -07001653 // Does the key match the crypto footer?
1654 if (rc == 0 && memcmp(scrypted_intermediate_key,
1655 crypt_ftr->scrypted_intermediate_key,
1656 sizeof(scrypted_intermediate_key)) == 0) {
1657 SLOGI("Password matches");
1658 rc = 0;
1659 } else {
1660 /* Try mounting the file system anyway, just in case the problem's with
1661 * the footer, not the key. */
George Burgess IV605d7ae2016-02-29 13:39:17 -08001662 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt",
1663 mount_point);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001664 mkdir(tmp_mount_point, 0755);
Paul Crowleye2ee1522017-09-26 14:05:26 -07001665 if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001666 SLOGE("Error temp mounting decrypted block device\n");
1667 delete_crypto_blk_dev(label);
1668
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001669 rc = ++crypt_ftr->failed_decrypt_count;
1670 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001671 } else {
1672 /* Success! */
1673 SLOGI("Password did not match but decrypted drive mounted - continue");
1674 umount(tmp_mount_point);
1675 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001676 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001677 }
1678
1679 if (rc == 0) {
1680 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001681 if (orig_failed_decrypt_count != 0) {
1682 put_crypt_ftr_and_key(crypt_ftr);
1683 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001684
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001685 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001686 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001687 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001688
1689 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001690 * the key when we want to change the password on it. */
Greg Kaiserfa099612018-02-14 11:26:00 -08001691 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001692 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001693 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001694 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001695 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001696
Paul Lawrence74f29f12014-08-28 15:54:10 -07001697 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001698 use_keymaster = keymaster_check_compatibility();
1699 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001700 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001701 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1702 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1703 upgrade = 1;
1704 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001705 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001706 upgrade = 1;
1707 }
1708
1709 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001710 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1711 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001712 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001713 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001714 }
1715 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001716
1717 // Do not fail even if upgrade failed - machine is bootable
1718 // Note that if this code is ever hit, there is a *serious* problem
1719 // since KDFs should never fail. You *must* fix the kdf before
1720 // proceeding!
1721 if (rc) {
1722 SLOGW("Upgrade failed with error %d,"
1723 " but continuing with previous state",
1724 rc);
1725 rc = 0;
1726 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001727 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001728 }
1729
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001730 errout:
1731 if (intermediate_key) {
1732 memset(intermediate_key, 0, intermediate_key_size);
1733 free(intermediate_key);
1734 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001735 return rc;
1736}
1737
Ken Sumrall29d8da82011-05-18 17:20:07 -07001738/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001739 * Called by vold when it's asked to mount an encrypted external
1740 * storage volume. The incoming partition has no crypto header/footer,
1741 * as any metadata is been stored in a separate, small partition.
1742 *
1743 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001744 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001745int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1746 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001747 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001748 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001749 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001750 return -1;
1751 }
1752
1753 unsigned long nr_sec = 0;
1754 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001755 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001756
Ken Sumrall29d8da82011-05-18 17:20:07 -07001757 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001758 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001759 return -1;
1760 }
1761
Jeff Sharkey9c484982015-03-31 10:35:33 -07001762 struct crypt_mnt_ftr ext_crypt_ftr;
1763 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1764 ext_crypt_ftr.fs_size = nr_sec;
1765 ext_crypt_ftr.keysize = keysize;
Greg Kaiserfa099612018-02-14 11:26:00 -08001766 strlcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256",
Jeff Sharkey32ebb732017-03-27 16:18:50 -06001767 MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001768
Paul Crowley5afbc622017-11-27 09:42:17 -08001769 return create_crypto_blk_dev(
1770 &ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label,
1771 e4crypt_is_native() ? CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE : 0);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001772}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001773
Jeff Sharkey9c484982015-03-31 10:35:33 -07001774/*
1775 * Called by vold when it's asked to unmount an encrypted external
1776 * storage volume.
1777 */
1778int cryptfs_revert_ext_volume(const char* label) {
1779 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001780}
1781
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001782int cryptfs_crypto_complete(void)
1783{
1784 return do_crypto_complete("/data");
1785}
1786
Paul Lawrencef4faa572014-01-29 13:31:03 -08001787int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1788{
1789 char encrypted_state[PROPERTY_VALUE_MAX];
1790 property_get("ro.crypto.state", encrypted_state, "");
1791 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1792 SLOGE("encrypted fs already validated or not running with encryption,"
1793 " aborting");
1794 return -1;
1795 }
1796
1797 if (get_crypt_ftr_and_key(crypt_ftr)) {
1798 SLOGE("Error getting crypt footer and key");
1799 return -1;
1800 }
1801
1802 return 0;
1803}
1804
Wei Wang4375f1b2017-02-24 17:43:01 -08001805int cryptfs_check_passwd(const char *passwd)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001806{
Paul Lawrence05335c32015-03-05 09:46:23 -08001807 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00001808 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001809 SLOGE("cryptfs_check_passwd not valid for file encryption");
1810 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001811 }
1812
Paul Lawrencef4faa572014-01-29 13:31:03 -08001813 struct crypt_mnt_ftr crypt_ftr;
1814 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001815
Paul Lawrencef4faa572014-01-29 13:31:03 -08001816 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001817 if (rc) {
1818 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001819 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001820 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001821
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001822 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001823 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1824 if (rc) {
1825 SLOGE("Password did not match");
1826 return rc;
1827 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001828
Paul Lawrence3d99eba2015-11-20 07:07:19 -08001829 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1830 // Here we have a default actual password but a real password
1831 // we must test against the scrypted value
1832 // First, we must delete the crypto block device that
1833 // test_mount_encrypted_fs leaves behind as a side effect
1834 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
1835 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
1836 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1837 if (rc) {
1838 SLOGE("Default password did not match on reboot encryption");
1839 return rc;
1840 }
1841
1842 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
1843 put_crypt_ftr_and_key(&crypt_ftr);
1844 rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
1845 if (rc) {
1846 SLOGE("Could not change password on reboot encryption");
1847 return rc;
1848 }
1849 }
1850
1851 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001852 cryptfs_clear_password();
1853 password = strdup(passwd);
1854 struct timespec now;
1855 clock_gettime(CLOCK_BOOTTIME, &now);
1856 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001857 }
1858
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001859 return rc;
1860}
1861
Jeff Sharkey83b559c2017-09-12 16:30:52 -06001862int cryptfs_verify_passwd(const char *passwd)
Ken Sumrall3ad90722011-10-04 20:38:29 -07001863{
1864 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser2c92d7b2018-02-14 11:26:08 -08001865 /* Allocate enough space for a 256 bit key, but we may use less */
1866 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001867 char encrypted_state[PROPERTY_VALUE_MAX];
1868 int rc;
1869
1870 property_get("ro.crypto.state", encrypted_state, "");
1871 if (strcmp(encrypted_state, "encrypted") ) {
1872 SLOGE("device not encrypted, aborting");
1873 return -2;
1874 }
1875
1876 if (!master_key_saved) {
1877 SLOGE("encrypted fs not yet mounted, aborting");
1878 return -1;
1879 }
1880
1881 if (!saved_mount_point) {
1882 SLOGE("encrypted fs failed to save mount point, aborting");
1883 return -1;
1884 }
1885
Ken Sumrall160b4d62013-04-22 12:15:39 -07001886 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001887 SLOGE("Error getting crypt footer and key\n");
1888 return -1;
1889 }
1890
1891 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1892 /* If the device has no password, then just say the password is valid */
1893 rc = 0;
1894 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001895 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001896 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1897 /* They match, the password is correct */
1898 rc = 0;
1899 } else {
1900 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1901 sleep(1);
1902 rc = 1;
1903 }
1904 }
1905
1906 return rc;
1907}
1908
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001909/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiserfa099612018-02-14 11:26:00 -08001910 * defaulted to 16 bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001911 * Presumably, at a minimum, the caller will update the
1912 * filesystem size and crypto_type_name after calling this function.
1913 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001914static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001915{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001916 off64_t off;
1917
1918 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001919 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001920 ftr->major_version = CURRENT_MAJOR_VERSION;
1921 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001922 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiserfa099612018-02-14 11:26:00 -08001923 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001924
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001925 switch (keymaster_check_compatibility()) {
1926 case 1:
1927 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1928 break;
1929
1930 case 0:
1931 ftr->kdf_type = KDF_SCRYPT;
1932 break;
1933
1934 default:
1935 SLOGE("keymaster_check_compatibility failed");
1936 return -1;
1937 }
1938
Kenny Rootc4c70f12013-06-14 12:11:38 -07001939 get_device_scrypt_params(ftr);
1940
Ken Sumrall160b4d62013-04-22 12:15:39 -07001941 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1942 if (get_crypt_ftr_info(NULL, &off) == 0) {
1943 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1944 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1945 ftr->persist_data_size;
1946 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001947
1948 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001949}
1950
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001951#define FRAMEWORK_BOOT_WAIT 60
1952
Paul Lawrence87999172014-02-20 12:21:31 -08001953static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
1954{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001955 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08001956 if (fd == -1) {
1957 SLOGE("Error opening file %s", filename);
1958 return -1;
1959 }
1960
1961 char block[CRYPT_INPLACE_BUFSIZE];
1962 memset(block, 0, sizeof(block));
1963 if (unix_read(fd, block, sizeof(block)) < 0) {
1964 SLOGE("Error reading file %s", filename);
1965 close(fd);
1966 return -1;
1967 }
1968
1969 close(fd);
1970
1971 SHA256_CTX c;
1972 SHA256_Init(&c);
1973 SHA256_Update(&c, block, sizeof(block));
1974 SHA256_Final(buf, &c);
1975
1976 return 0;
1977}
1978
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001979static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
1980 char* real_blkdev, int previously_encrypted_upto) {
Paul Lawrence87999172014-02-20 12:21:31 -08001981 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08001982 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08001983
Paul Lawrence87999172014-02-20 12:21:31 -08001984 /* The size of the userdata partition, and add in the vold volumes below */
1985 tot_encryption_size = crypt_ftr->fs_size;
1986
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001987 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08001988 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08001989
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001990 if (rc == ENABLE_INPLACE_ERR_DEV) {
1991 /* Hack for b/17898962 */
1992 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
1993 cryptfs_reboot(RebootType::reboot);
1994 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07001995
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08001996 if (!rc) {
1997 crypt_ftr->encrypted_upto = cur_encryption_done;
1998 }
Paul Lawrence87999172014-02-20 12:21:31 -08001999
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002000 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2001 /* The inplace routine never actually sets the progress to 100% due
2002 * to the round down nature of integer division, so set it here */
2003 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002004 }
2005
2006 return rc;
2007}
2008
Paul Crowleyb64933a2017-10-31 08:25:55 -07002009static int vold_unmountAll(void) {
2010 VolumeManager* vm = VolumeManager::Instance();
2011 return vm->unmountAll();
2012}
2013
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002014int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Lawrence87999172014-02-20 12:21:31 -08002015 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Greg Kaiser2c92d7b2018-02-14 11:26:08 -08002016 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002017 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002018 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002019 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002020 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002021 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002022 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002023 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002024 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002025 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002026 bool onlyCreateHeader = false;
2027 int fd = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002028
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002029 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002030 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2031 /* An encryption was underway and was interrupted */
2032 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2033 crypt_ftr.encrypted_upto = 0;
2034 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002035
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002036 /* At this point, we are in an inconsistent state. Until we successfully
2037 complete encryption, a reboot will leave us broken. So mark the
2038 encryption failed in case that happens.
2039 On successfully completing encryption, remove this flag */
2040 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002041
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002042 put_crypt_ftr_and_key(&crypt_ftr);
2043 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2044 if (!check_ftr_sha(&crypt_ftr)) {
2045 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2046 put_crypt_ftr_and_key(&crypt_ftr);
2047 goto error_unencrypted;
2048 }
2049
2050 /* Doing a reboot-encryption*/
2051 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2052 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2053 rebootEncryption = true;
2054 }
Paul Lawrence87999172014-02-20 12:21:31 -08002055 }
2056
2057 property_get("ro.crypto.state", encrypted_state, "");
2058 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2059 SLOGE("Device is already running encrypted, aborting");
2060 goto error_unencrypted;
2061 }
2062
2063 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002064 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2065 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002066
Ken Sumrall3ed82362011-01-28 23:31:16 -08002067 /* Get the size of the real block device */
Wei Wang4375f1b2017-02-24 17:43:01 -08002068 fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002069 if (fd == -1) {
2070 SLOGE("Cannot open block device %s\n", real_blkdev);
2071 goto error_unencrypted;
2072 }
2073 unsigned long nr_sec;
2074 get_blkdev_size(fd, &nr_sec);
2075 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002076 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2077 goto error_unencrypted;
2078 }
2079 close(fd);
2080
2081 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002082 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002083 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002084 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002085 if (fs_size_sec == 0)
2086 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2087
Paul Lawrence87999172014-02-20 12:21:31 -08002088 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002089
2090 if (fs_size_sec > max_fs_size_sec) {
2091 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2092 goto error_unencrypted;
2093 }
2094 }
2095
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002096 /* Get a wakelock as this may take a while, and we don't want the
2097 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2098 * wants to keep the screen on, it can grab a full wakelock.
2099 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002100 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002101 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2102
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002103 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002104 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002105 */
2106 property_set("vold.decrypt", "trigger_shutdown_framework");
2107 SLOGD("Just asked init to shut down class main\n");
2108
Jeff Sharkey9c484982015-03-31 10:35:33 -07002109 /* Ask vold to unmount all devices that it manages */
2110 if (vold_unmountAll()) {
2111 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002112 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002113
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002114 /* no_ui means we are being called from init, not settings.
2115 Now we always reboot from settings, so !no_ui means reboot
2116 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002117 if (!no_ui) {
2118 /* Try fallback, which is to reboot and try there */
2119 onlyCreateHeader = true;
2120 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2121 if (breadcrumb == 0) {
2122 SLOGE("Failed to create breadcrumb file");
2123 goto error_shutting_down;
2124 }
2125 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002126 }
2127
2128 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002129 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002130 /* Now that /data is unmounted, we need to mount a tmpfs
2131 * /data, set a property saying we're doing inplace encryption,
2132 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002133 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002134 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002135 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002136 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002137 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002138 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002139
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002140 /* restart the framework. */
2141 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002142 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002143
Ken Sumrall92736ef2012-10-17 20:57:14 -07002144 /* Ugh, shutting down the framework is not synchronous, so until it
2145 * can be fixed, this horrible hack will wait a moment for it all to
2146 * shut down before proceeding. Without it, some devices cannot
2147 * restart the graphics services.
2148 */
2149 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002150 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002151
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002152 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002153 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002154 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002155 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2156 goto error_shutting_down;
2157 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002158
Paul Lawrence87999172014-02-20 12:21:31 -08002159 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2160 crypt_ftr.fs_size = nr_sec
2161 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2162 } else {
2163 crypt_ftr.fs_size = nr_sec;
2164 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002165 /* At this point, we are in an inconsistent state. Until we successfully
2166 complete encryption, a reboot will leave us broken. So mark the
2167 encryption failed in case that happens.
2168 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002169 if (onlyCreateHeader) {
2170 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2171 } else {
2172 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2173 }
Paul Lawrence87999172014-02-20 12:21:31 -08002174 crypt_ftr.crypt_type = crypt_type;
Greg Kaiserfa099612018-02-14 11:26:00 -08002175 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002176
Paul Lawrence87999172014-02-20 12:21:31 -08002177 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002178 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2179 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002180 SLOGE("Cannot create encrypted master key\n");
2181 goto error_shutting_down;
2182 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002183
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002184 /* Replace scrypted intermediate key if we are preparing for a reboot */
2185 if (onlyCreateHeader) {
Greg Kaiserfa099612018-02-14 11:26:00 -08002186 unsigned char fake_master_key[KEY_LEN_BYTES];
2187 unsigned char encrypted_fake_master_key[KEY_LEN_BYTES];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002188 memset(fake_master_key, 0, sizeof(fake_master_key));
2189 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
2190 encrypted_fake_master_key, &crypt_ftr);
2191 }
2192
Paul Lawrence87999172014-02-20 12:21:31 -08002193 /* Write the key to the end of the partition */
2194 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002195
Paul Lawrence87999172014-02-20 12:21:31 -08002196 /* If any persistent data has been remembered, save it.
2197 * If none, create a valid empty table and save that.
2198 */
2199 if (!persist_data) {
Wei Wang4375f1b2017-02-24 17:43:01 -08002200 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002201 if (pdata) {
2202 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2203 persist_data = pdata;
2204 }
2205 }
2206 if (persist_data) {
2207 save_persistent_data();
2208 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002209 }
2210
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002211 if (onlyCreateHeader) {
2212 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002213 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002214 }
2215
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002216 if (!no_ui || rebootEncryption) {
Ajay Dudani87701e22014-09-17 21:02:52 -07002217 /* startup service classes main and late_start */
2218 property_set("vold.decrypt", "trigger_restart_min_framework");
2219 SLOGD("Just triggered restart_min_framework\n");
2220
2221 /* OK, the framework is restarted and will soon be showing a
2222 * progress bar. Time to setup an encrypted mapping, and
2223 * either write a new filesystem, or encrypt in place updating
2224 * the progress bar as we work.
2225 */
2226 }
2227
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002228 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002229 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002230 CRYPTO_BLOCK_DEVICE, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002231
Paul Lawrence87999172014-02-20 12:21:31 -08002232 /* If we are continuing, check checksums match */
2233 rc = 0;
2234 if (previously_encrypted_upto) {
2235 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2236 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002237
Paul Lawrence87999172014-02-20 12:21:31 -08002238 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2239 sizeof(hash_first_block)) != 0) {
2240 SLOGE("Checksums do not match - trigger wipe");
2241 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002242 }
2243 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002244
Paul Lawrence87999172014-02-20 12:21:31 -08002245 if (!rc) {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002246 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002247 previously_encrypted_upto);
2248 }
2249
2250 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002251 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002252 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2253 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002254 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002255 SLOGE("Error calculating checksum for continuing encryption");
2256 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002257 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002258 }
2259
2260 /* Undo the dm-crypt mapping whether we succeed or not */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002261 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002262
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002263 if (! rc) {
2264 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002265 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002266
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002267 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002268 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2269 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002270 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002271 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002272
Paul Lawrence6bfed202014-07-28 12:47:22 -07002273 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002274
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002275 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2276 char value[PROPERTY_VALUE_MAX];
2277 property_get("ro.crypto.state", value, "");
2278 if (!strcmp(value, "")) {
2279 /* default encryption - continue first boot sequence */
2280 property_set("ro.crypto.state", "encrypted");
2281 property_set("ro.crypto.type", "block");
2282 release_wake_lock(lockid);
2283 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2284 // Bring up cryptkeeper that will check the password and set it
2285 property_set("vold.decrypt", "trigger_shutdown_framework");
2286 sleep(2);
2287 property_set("vold.encrypt_progress", "");
2288 cryptfs_trigger_restart_min_framework();
2289 } else {
2290 cryptfs_check_passwd(DEFAULT_PASSWORD);
2291 cryptfs_restart_internal(1);
2292 }
2293 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002294 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002295 sleep(2); /* Give the UI a chance to show 100% progress */
2296 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002297 }
Paul Lawrence87999172014-02-20 12:21:31 -08002298 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002299 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002300 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002301 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002302 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002303 char value[PROPERTY_VALUE_MAX];
2304
Ken Sumrall319369a2012-06-27 16:30:18 -07002305 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002306 if (!strcmp(value, "1")) {
2307 /* wipe data if encryption failed */
2308 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002309 std::string err;
2310 const std::vector<std::string> options = {
2311 "--wipe_data\n--reason=cryptfs_enable_internal\n"
2312 };
2313 if (!write_bootloader_message(options, &err)) {
2314 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002315 }
Josh Gaofec44372017-08-28 13:22:55 -07002316 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002317 } else {
2318 /* set property to trigger dialog */
2319 property_set("vold.encrypt_progress", "error_partially_encrypted");
2320 release_wake_lock(lockid);
2321 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002322 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002323 }
2324
Ken Sumrall3ed82362011-01-28 23:31:16 -08002325 /* hrm, the encrypt step claims success, but the reboot failed.
2326 * This should not happen.
2327 * Set the property and return. Hope the framework can deal with it.
2328 */
2329 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002330 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002331 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002332
2333error_unencrypted:
2334 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002335 if (lockid[0]) {
2336 release_wake_lock(lockid);
2337 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002338 return -1;
2339
2340error_shutting_down:
2341 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2342 * but the framework is stopped and not restarted to show the error, so it's up to
2343 * vold to restart the system.
2344 */
2345 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Josh Gaofec44372017-08-28 13:22:55 -07002346 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002347
2348 /* shouldn't get here */
2349 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002350 if (lockid[0]) {
2351 release_wake_lock(lockid);
2352 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002353 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002354}
2355
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002356int cryptfs_enable(int type, const char* passwd, int no_ui) {
2357 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002358}
2359
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002360int cryptfs_enable_default(int no_ui) {
2361 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002362}
2363
2364int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002365{
Paul Crowley38132a12016-02-09 09:50:32 +00002366 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002367 SLOGE("cryptfs_changepw not valid for file encryption");
2368 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002369 }
2370
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002371 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002372 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002373
2374 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002375 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002376 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002377 return -1;
2378 }
2379
Paul Lawrencef4faa572014-01-29 13:31:03 -08002380 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2381 SLOGE("Invalid crypt_type %d", crypt_type);
2382 return -1;
2383 }
2384
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002385 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002386 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002387 SLOGE("Error getting crypt footer and key");
2388 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002389 }
2390
Paul Lawrencef4faa572014-01-29 13:31:03 -08002391 crypt_ftr.crypt_type = crypt_type;
2392
JP Abgrall933216c2015-02-11 13:44:32 -08002393 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08002394 : newpw,
2395 crypt_ftr.salt,
2396 saved_master_key,
2397 crypt_ftr.master_key,
2398 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08002399 if (rc) {
2400 SLOGE("Encrypt master key failed: %d", rc);
2401 return -1;
2402 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002403 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002404 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002405
2406 return 0;
2407}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002408
Rubin Xu85c01f92014-10-13 12:49:54 +01002409static unsigned int persist_get_max_entries(int encrypted) {
2410 struct crypt_mnt_ftr crypt_ftr;
2411 unsigned int dsize;
2412 unsigned int max_persistent_entries;
2413
2414 /* If encrypted, use the values from the crypt_ftr, otherwise
2415 * use the values for the current spec.
2416 */
2417 if (encrypted) {
2418 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2419 return -1;
2420 }
2421 dsize = crypt_ftr.persist_data_size;
2422 } else {
2423 dsize = CRYPT_PERSIST_DATA_SIZE;
2424 }
2425
2426 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2427 sizeof(struct crypt_persist_entry);
2428
2429 return max_persistent_entries;
2430}
2431
2432static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002433{
2434 unsigned int i;
2435
2436 if (persist_data == NULL) {
2437 return -1;
2438 }
2439 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2440 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2441 /* We found it! */
2442 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2443 return 0;
2444 }
2445 }
2446
2447 return -1;
2448}
2449
Rubin Xu85c01f92014-10-13 12:49:54 +01002450static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002451{
2452 unsigned int i;
2453 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002454 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002455
2456 if (persist_data == NULL) {
2457 return -1;
2458 }
2459
Rubin Xu85c01f92014-10-13 12:49:54 +01002460 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002461
2462 num = persist_data->persist_valid_entries;
2463
2464 for (i = 0; i < num; i++) {
2465 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2466 /* We found an existing entry, update it! */
2467 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2468 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2469 return 0;
2470 }
2471 }
2472
2473 /* We didn't find it, add it to the end, if there is room */
2474 if (persist_data->persist_valid_entries < max_persistent_entries) {
2475 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2476 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2477 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2478 persist_data->persist_valid_entries++;
2479 return 0;
2480 }
2481
2482 return -1;
2483}
2484
Rubin Xu85c01f92014-10-13 12:49:54 +01002485/**
2486 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
2487 * sequence and its index is greater than or equal to index. Return 0 otherwise.
2488 */
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002489int match_multi_entry(const char *key, const char *field, unsigned index) {
2490 std::string key_ = key;
2491 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01002492
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002493 std::string parsed_field;
2494 unsigned parsed_index;
2495
2496 std::string::size_type split = key_.find_last_of('_');
2497 if (split == std::string::npos) {
2498 parsed_field = key_;
2499 parsed_index = 0;
2500 } else {
2501 parsed_field = key_.substr(0, split);
2502 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01002503 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06002504
2505 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01002506}
2507
2508/*
2509 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
2510 * remaining entries starting from index will be deleted.
2511 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
2512 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
2513 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
2514 *
2515 */
2516static int persist_del_keys(const char *fieldname, unsigned index)
2517{
2518 unsigned int i;
2519 unsigned int j;
2520 unsigned int num;
2521
2522 if (persist_data == NULL) {
2523 return PERSIST_DEL_KEY_ERROR_OTHER;
2524 }
2525
2526 num = persist_data->persist_valid_entries;
2527
2528 j = 0; // points to the end of non-deleted entries.
2529 // Filter out to-be-deleted entries in place.
2530 for (i = 0; i < num; i++) {
2531 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
2532 persist_data->persist_entry[j] = persist_data->persist_entry[i];
2533 j++;
2534 }
2535 }
2536
2537 if (j < num) {
2538 persist_data->persist_valid_entries = j;
2539 // Zeroise the remaining entries
2540 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
2541 return PERSIST_DEL_KEY_OK;
2542 } else {
2543 // Did not find an entry matching the given fieldname
2544 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
2545 }
2546}
2547
2548static int persist_count_keys(const char *fieldname)
2549{
2550 unsigned int i;
2551 unsigned int count;
2552
2553 if (persist_data == NULL) {
2554 return -1;
2555 }
2556
2557 count = 0;
2558 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2559 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
2560 count++;
2561 }
2562 }
2563
2564 return count;
2565}
2566
Ken Sumrall160b4d62013-04-22 12:15:39 -07002567/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002568int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002569{
Paul Crowley38132a12016-02-09 09:50:32 +00002570 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002571 SLOGE("Cannot get field when file encrypted");
2572 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002573 }
2574
Ken Sumrall160b4d62013-04-22 12:15:39 -07002575 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002576 /* CRYPTO_GETFIELD_OK is success,
2577 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
2578 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
2579 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07002580 */
Rubin Xu85c01f92014-10-13 12:49:54 +01002581 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
2582 int i;
2583 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002584
2585 if (persist_data == NULL) {
2586 load_persistent_data();
2587 if (persist_data == NULL) {
2588 SLOGE("Getfield error, cannot load persistent data");
2589 goto out;
2590 }
2591 }
2592
Rubin Xu85c01f92014-10-13 12:49:54 +01002593 // Read value from persistent entries. If the original value is split into multiple entries,
2594 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07002595 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01002596 // We found it, copy it to the caller's buffer and keep going until all entries are read.
2597 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
2598 // value too small
2599 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2600 goto out;
2601 }
2602 rc = CRYPTO_GETFIELD_OK;
2603
2604 for (i = 1; /* break explicitly */; i++) {
2605 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
2606 (int) sizeof(temp_field)) {
2607 // If the fieldname is very long, we stop as soon as it begins to overflow the
2608 // maximum field length. At this point we have in fact fully read out the original
2609 // value because cryptfs_setfield would not allow fields with longer names to be
2610 // written in the first place.
2611 break;
2612 }
2613 if (!persist_get_key(temp_field, temp_value)) {
2614 if (strlcat(value, temp_value, len) >= (unsigned)len) {
2615 // value too small.
2616 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
2617 goto out;
2618 }
2619 } else {
2620 // Exhaust all entries.
2621 break;
2622 }
2623 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002624 } else {
2625 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01002626 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002627 }
2628
2629out:
2630 return rc;
2631}
2632
2633/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01002634int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07002635{
Paul Crowley38132a12016-02-09 09:50:32 +00002636 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08002637 SLOGE("Cannot set field when file encrypted");
2638 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07002639 }
2640
Ken Sumrall160b4d62013-04-22 12:15:39 -07002641 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01002642 /* 0 is success, negative values are error */
2643 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002644 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01002645 unsigned int field_id;
2646 char temp_field[PROPERTY_KEY_MAX];
2647 unsigned int num_entries;
2648 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002649
2650 if (persist_data == NULL) {
2651 load_persistent_data();
2652 if (persist_data == NULL) {
2653 SLOGE("Setfield error, cannot load persistent data");
2654 goto out;
2655 }
2656 }
2657
2658 property_get("ro.crypto.state", encrypted_state, "");
2659 if (!strcmp(encrypted_state, "encrypted") ) {
2660 encrypted = 1;
2661 }
2662
Rubin Xu85c01f92014-10-13 12:49:54 +01002663 // Compute the number of entries required to store value, each entry can store up to
2664 // (PROPERTY_VALUE_MAX - 1) chars
2665 if (strlen(value) == 0) {
2666 // Empty value also needs one entry to store.
2667 num_entries = 1;
2668 } else {
2669 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
2670 }
2671
2672 max_keylen = strlen(fieldname);
2673 if (num_entries > 1) {
2674 // Need an extra "_%d" suffix.
2675 max_keylen += 1 + log10(num_entries);
2676 }
2677 if (max_keylen > PROPERTY_KEY_MAX - 1) {
2678 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002679 goto out;
2680 }
2681
Rubin Xu85c01f92014-10-13 12:49:54 +01002682 // Make sure we have enough space to write the new value
2683 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
2684 persist_get_max_entries(encrypted)) {
2685 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
2686 goto out;
2687 }
2688
2689 // Now that we know persist_data has enough space for value, let's delete the old field first
2690 // to make up space.
2691 persist_del_keys(fieldname, 0);
2692
2693 if (persist_set_key(fieldname, value, encrypted)) {
2694 // fail to set key, should not happen as we have already checked the available space
2695 SLOGE("persist_set_key() error during setfield()");
2696 goto out;
2697 }
2698
2699 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08002700 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01002701
2702 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
2703 // fail to set key, should not happen as we have already checked the available space.
2704 SLOGE("persist_set_key() error during setfield()");
2705 goto out;
2706 }
2707 }
2708
Ken Sumrall160b4d62013-04-22 12:15:39 -07002709 /* If we are running encrypted, save the persistent data now */
2710 if (encrypted) {
2711 if (save_persistent_data()) {
2712 SLOGE("Setfield error, cannot save persistent data");
2713 goto out;
2714 }
2715 }
2716
Rubin Xu85c01f92014-10-13 12:49:54 +01002717 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002718
2719out:
2720 return rc;
2721}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002722
2723/* Checks userdata. Attempt to mount the volume if default-
2724 * encrypted.
2725 * On success trigger next init phase and return 0.
2726 * Currently do not handle failure - see TODO below.
2727 */
2728int cryptfs_mount_default_encrypted(void)
2729{
Paul Lawrence84274cc2016-04-15 15:41:33 -07002730 int crypt_type = cryptfs_get_password_type();
2731 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2732 SLOGE("Bad crypt type - error");
2733 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2734 SLOGD("Password is not default - "
2735 "starting min framework to prompt");
2736 property_set("vold.decrypt", "trigger_restart_min_framework");
2737 return 0;
2738 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2739 SLOGD("Password is default - restarting filesystem");
2740 cryptfs_restart_internal(0);
2741 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08002742 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07002743 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002744 }
2745
Paul Lawrence6bfed202014-07-28 12:47:22 -07002746 /** Corrupt. Allow us to boot into framework, which will detect bad
2747 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002748 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002749 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002750 return 0;
2751}
2752
2753/* Returns type of the password, default, pattern, pin or password.
2754 */
2755int cryptfs_get_password_type(void)
2756{
Paul Crowley38132a12016-02-09 09:50:32 +00002757 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002758 SLOGE("cryptfs_get_password_type not valid for file encryption");
2759 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002760 }
2761
Paul Lawrencef4faa572014-01-29 13:31:03 -08002762 struct crypt_mnt_ftr crypt_ftr;
2763
2764 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2765 SLOGE("Error getting crypt footer and key\n");
2766 return -1;
2767 }
2768
Paul Lawrence6bfed202014-07-28 12:47:22 -07002769 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2770 return -1;
2771 }
2772
Paul Lawrencef4faa572014-01-29 13:31:03 -08002773 return crypt_ftr.crypt_type;
2774}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002775
Paul Lawrence05335c32015-03-05 09:46:23 -08002776const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002777{
Paul Crowley38132a12016-02-09 09:50:32 +00002778 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002779 SLOGE("cryptfs_get_password not valid for file encryption");
2780 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08002781 }
2782
Paul Lawrence399317e2014-03-10 13:20:50 -07002783 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08002784 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07002785 if (now.tv_sec < password_expiry_time) {
2786 return password;
2787 } else {
2788 cryptfs_clear_password();
2789 return 0;
2790 }
2791}
2792
2793void cryptfs_clear_password()
2794{
2795 if (password) {
2796 size_t len = strlen(password);
2797 memset(password, 0, len);
2798 free(password);
2799 password = 0;
2800 password_expiry_time = 0;
2801 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002802}
Paul Lawrence731a7a22015-04-28 22:14:15 +00002803
Paul Lawrence0c247462015-10-29 10:30:57 -07002804int cryptfs_isConvertibleToFBE()
2805{
Paul Crowleye2ee1522017-09-26 14:05:26 -07002806 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Paul Lawrence0c247462015-10-29 10:30:57 -07002807 return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
2808}