blob: 735232d79472e803f0a67bbee05dca5ee142448f [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>
Ken Sumrall3ed82362011-01-28 23:31:16 -080041#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070042#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070043#include <fs_mgr.h>
Paul Lawrence9c58a872014-09-30 09:12:51 -070044#include <time.h>
Rubin Xu85c01f92014-10-13 12:49:54 +010045#include <math.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080046#include "cryptfs.h"
47#define LOG_TAG "Cryptfs"
48#include "cutils/log.h"
49#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070050#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080051#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070052#include <logwrap/logwrap.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070053#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070054#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070055#include "crypto_scrypt.h"
Paul Lawrence05335c32015-03-05 09:46:23 -080056#include "ext4_crypt.h"
Paul Lawrenceae59fe62014-01-21 08:23:27 -080057#include "ext4_utils.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000058#include "f2fs_sparseblock.h"
Paul Lawrence87999172014-02-20 12:21:31 -080059#include "CheckBattery.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080060#include "Process.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080061
Shawn Willden8af33352015-02-24 09:51:34 -070062#include <hardware/keymaster0.h>
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070063
Mark Salyzyn3e971272014-01-21 13:27:04 -080064#define UNUSED __attribute__((unused))
65
Mark Salyzyn5eecc442014-02-12 14:16:14 -080066#define UNUSED __attribute__((unused))
67
Ajay Dudani87701e22014-09-17 21:02:52 -070068#ifdef CONFIG_HW_DISK_ENCRYPTION
69#include "cryptfs_hw.h"
70#endif
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
75#define KEY_LEN_BYTES 16
76#define IV_LEN_BYTES 16
77
Ken Sumrall29d8da82011-05-18 17:20:07 -070078#define KEY_IN_FOOTER "footer"
79
Paul Lawrencef4faa572014-01-29 13:31:03 -080080// "default_password" encoded into hex (d=0x64 etc)
81#define DEFAULT_PASSWORD "64656661756c745f70617373776f7264"
82
Ken Sumrall29d8da82011-05-18 17:20:07 -070083#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070084#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070085
Ken Sumralle919efe2012-09-29 17:07:41 -070086#define TABLE_LOAD_RETRIES 10
87
Shawn Willden47ba10d2014-09-03 17:07:06 -060088#define RSA_KEY_SIZE 2048
89#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
90#define RSA_EXPONENT 0x10001
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070091
Paul Lawrence8e3f4512014-09-08 10:11:17 -070092#define RETRY_MOUNT_ATTEMPTS 10
93#define RETRY_MOUNT_DELAY_SECONDS 1
94
Ken Sumrall8f869aa2010-12-03 03:47:09 -080095char *me = "cryptfs";
96
Jason parks70a4b3f2011-01-28 10:10:47 -060097static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070098static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060099static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700100static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800101
Shawn Willden8af33352015-02-24 09:51:34 -0700102static int keymaster_init(keymaster0_device_t **keymaster_dev)
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700103{
104 int rc;
105
106 const hw_module_t* mod;
107 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
108 if (rc) {
109 ALOGE("could not find any keystore module");
110 goto out;
111 }
112
Shawn Willden8af33352015-02-24 09:51:34 -0700113 rc = keymaster0_open(mod, keymaster_dev);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700114 if (rc) {
115 ALOGE("could not open keymaster device in %s (%s)",
116 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
117 goto out;
118 }
119
120 return 0;
121
122out:
123 *keymaster_dev = NULL;
124 return rc;
125}
126
127/* Should we use keymaster? */
128static int keymaster_check_compatibility()
129{
Shawn Willden8af33352015-02-24 09:51:34 -0700130 keymaster0_device_t *keymaster_dev = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700131 int rc = 0;
132
133 if (keymaster_init(&keymaster_dev)) {
134 SLOGE("Failed to init keymaster");
135 rc = -1;
136 goto out;
137 }
138
Paul Lawrence8c008392014-05-06 14:02:48 -0700139 SLOGI("keymaster version is %d", keymaster_dev->common.module->module_api_version);
140
141 if (keymaster_dev->common.module->module_api_version
142 < KEYMASTER_MODULE_API_VERSION_0_3) {
143 rc = 0;
144 goto out;
145 }
146
Shawn Willden7c49ab02014-10-30 08:12:32 -0600147 if (!(keymaster_dev->flags & KEYMASTER_SOFTWARE_ONLY) &&
148 (keymaster_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE)) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700149 rc = 1;
150 }
151
152out:
Shawn Willden8af33352015-02-24 09:51:34 -0700153 keymaster0_close(keymaster_dev);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700154 return rc;
155}
156
157/* Create a new keymaster key and store it in this footer */
158static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
159{
160 uint8_t* key = 0;
Shawn Willden8af33352015-02-24 09:51:34 -0700161 keymaster0_device_t *keymaster_dev = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700162
163 if (keymaster_init(&keymaster_dev)) {
164 SLOGE("Failed to init keymaster");
165 return -1;
166 }
167
168 int rc = 0;
169
170 keymaster_rsa_keygen_params_t params;
171 memset(&params, '\0', sizeof(params));
Shawn Willden47ba10d2014-09-03 17:07:06 -0600172 params.public_exponent = RSA_EXPONENT;
173 params.modulus_size = RSA_KEY_SIZE;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700174
175 size_t key_size;
176 if (keymaster_dev->generate_keypair(keymaster_dev, TYPE_RSA, &params,
177 &key, &key_size)) {
178 SLOGE("Failed to generate keypair");
179 rc = -1;
180 goto out;
181 }
182
183 if (key_size > KEYMASTER_BLOB_SIZE) {
184 SLOGE("Keymaster key too large for crypto footer");
185 rc = -1;
186 goto out;
187 }
188
189 memcpy(ftr->keymaster_blob, key, key_size);
190 ftr->keymaster_blob_size = key_size;
191
192out:
Shawn Willden8af33352015-02-24 09:51:34 -0700193 keymaster0_close(keymaster_dev);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700194 free(key);
195 return rc;
196}
197
Shawn Willdene17a9c42014-09-08 13:04:08 -0600198/* This signs the given object using the keymaster key. */
199static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600200 const unsigned char *object,
201 const size_t object_size,
202 unsigned char **signature,
203 size_t *signature_size)
204{
205 int rc = 0;
Shawn Willden8af33352015-02-24 09:51:34 -0700206 keymaster0_device_t *keymaster_dev = 0;
Shawn Willden47ba10d2014-09-03 17:07:06 -0600207 if (keymaster_init(&keymaster_dev)) {
208 SLOGE("Failed to init keymaster");
209 return -1;
210 }
211
212 /* We currently set the digest type to DIGEST_NONE because it's the
213 * only supported value for keymaster. A similar issue exists with
214 * PADDING_NONE. Long term both of these should likely change.
215 */
216 keymaster_rsa_sign_params_t params;
217 params.digest_type = DIGEST_NONE;
218 params.padding_type = PADDING_NONE;
219
220 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600221 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600222 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600223
Shawn Willdene17a9c42014-09-08 13:04:08 -0600224 // To sign a message with RSA, the message must satisfy two
225 // constraints:
226 //
227 // 1. The message, when interpreted as a big-endian numeric value, must
228 // be strictly less than the public modulus of the RSA key. Note
229 // that because the most significant bit of the public modulus is
230 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
231 // key), an n-bit message with most significant bit 0 always
232 // satisfies this requirement.
233 //
234 // 2. The message must have the same length in bits as the public
235 // modulus of the RSA key. This requirement isn't mathematically
236 // necessary, but is necessary to ensure consistency in
237 // implementations.
238 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600239 case KDF_SCRYPT_KEYMASTER:
240 // This ensures the most significant byte of the signed message
241 // is zero. We could have zero-padded to the left instead, but
242 // this approach is slightly more robust against changes in
243 // object size. However, it's still broken (but not unusably
244 // so) because we really should be using a proper RSA padding
245 // function, such as OAEP.
246 //
247 // TODO(paullawrence): When keymaster 0.4 is available, change
248 // this to use the padding options it provides.
249 memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
250 SLOGI("Signing safely-padded object");
251 break;
252 default:
253 SLOGE("Unknown KDF type %d", ftr->kdf_type);
254 return -1;
255 }
256
Shawn Willden47ba10d2014-09-03 17:07:06 -0600257 rc = keymaster_dev->sign_data(keymaster_dev,
258 &params,
259 ftr->keymaster_blob,
260 ftr->keymaster_blob_size,
261 to_sign,
Shawn Willdene17a9c42014-09-08 13:04:08 -0600262 to_sign_size,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600263 signature,
264 signature_size);
265
Shawn Willden8af33352015-02-24 09:51:34 -0700266 keymaster0_close(keymaster_dev);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600267 return rc;
268}
269
Paul Lawrence399317e2014-03-10 13:20:50 -0700270/* Store password when userdata is successfully decrypted and mounted.
271 * Cleared by cryptfs_clear_password
272 *
273 * To avoid a double prompt at boot, we need to store the CryptKeeper
274 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
275 * Since the entire framework is torn down and rebuilt after encryption,
276 * we have to use a daemon or similar to store the password. Since vold
277 * is secured against IPC except from system processes, it seems a reasonable
278 * place to store this.
279 *
280 * password should be cleared once it has been used.
281 *
282 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800283 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700284static char* password = 0;
285static int password_expiry_time = 0;
286static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800287
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800288extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800289
Paul Lawrence87999172014-02-20 12:21:31 -0800290enum RebootType {reboot, recovery, shutdown};
291static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700292{
Paul Lawrence87999172014-02-20 12:21:31 -0800293 switch(rt) {
294 case reboot:
295 property_set(ANDROID_RB_PROPERTY, "reboot");
296 break;
297
298 case recovery:
299 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
300 break;
301
302 case shutdown:
303 property_set(ANDROID_RB_PROPERTY, "shutdown");
304 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700305 }
Paul Lawrence87999172014-02-20 12:21:31 -0800306
Ken Sumralladfba362013-06-04 16:37:52 -0700307 sleep(20);
308
309 /* Shouldn't get here, reboot should happen before sleep times out */
310 return;
311}
312
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800313static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
314{
315 memset(io, 0, dataSize);
316 io->data_size = dataSize;
317 io->data_start = sizeof(struct dm_ioctl);
318 io->version[0] = 4;
319 io->version[1] = 0;
320 io->version[2] = 0;
321 io->flags = flags;
322 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100323 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800324 }
325}
326
Kenny Rootc4c70f12013-06-14 12:11:38 -0700327/**
328 * Gets the default device scrypt parameters for key derivation time tuning.
329 * The parameters should lead to about one second derivation time for the
330 * given device.
331 */
332static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
333 const int default_params[] = SCRYPT_DEFAULTS;
334 int params[] = SCRYPT_DEFAULTS;
335 char paramstr[PROPERTY_VALUE_MAX];
336 char *token;
337 char *saveptr;
338 int i;
339
340 property_get(SCRYPT_PROP, paramstr, "");
341 if (paramstr[0] != '\0') {
342 /*
343 * The token we're looking for should be three integers separated by
344 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
345 */
Kenny Root2947e342013-08-14 15:54:49 -0700346 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
347 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700348 i++, token = strtok_r(NULL, ":", &saveptr)) {
349 char *endptr;
350 params[i] = strtol(token, &endptr, 10);
351
352 /*
353 * Check that there was a valid number and it's 8-bit. If not,
354 * break out and the end check will take the default values.
355 */
356 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
357 break;
358 }
359 }
360
361 /*
362 * If there were not enough tokens or a token was malformed (not an
363 * integer), it will end up here and the default parameters can be
364 * taken.
365 */
366 if ((i != 3) || (token != NULL)) {
367 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
368 memcpy(params, default_params, sizeof(params));
369 }
370 }
371
372 ftr->N_factor = params[0];
373 ftr->r_factor = params[1];
374 ftr->p_factor = params[2];
375}
376
Ken Sumrall3ed82362011-01-28 23:31:16 -0800377static unsigned int get_fs_size(char *dev)
378{
379 int fd, block_size;
380 struct ext4_super_block sb;
381 off64_t len;
382
383 if ((fd = open(dev, O_RDONLY)) < 0) {
384 SLOGE("Cannot open device to get filesystem size ");
385 return 0;
386 }
387
388 if (lseek64(fd, 1024, SEEK_SET) < 0) {
389 SLOGE("Cannot seek to superblock");
390 return 0;
391 }
392
393 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
394 SLOGE("Cannot read superblock");
395 return 0;
396 }
397
398 close(fd);
399
Daniel Rosenberge82df162014-08-15 22:19:23 +0000400 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
401 SLOGE("Not a valid ext4 superblock");
402 return 0;
403 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800404 block_size = 1024 << sb.s_log_block_size;
405 /* compute length in bytes */
406 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
407
408 /* return length in sectors */
409 return (unsigned int) (len / 512);
410}
411
Ken Sumrall160b4d62013-04-22 12:15:39 -0700412static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
413{
414 static int cached_data = 0;
415 static off64_t cached_off = 0;
416 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
417 int fd;
418 char key_loc[PROPERTY_VALUE_MAX];
419 char real_blkdev[PROPERTY_VALUE_MAX];
420 unsigned int nr_sec;
421 int rc = -1;
422
423 if (!cached_data) {
424 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
425
426 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
427 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
428 SLOGE("Cannot open real block device %s\n", real_blkdev);
429 return -1;
430 }
431
432 if ((nr_sec = get_blkdev_size(fd))) {
433 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
434 * encryption info footer and key, and plenty of bytes to spare for future
435 * growth.
436 */
437 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
438 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
439 cached_data = 1;
440 } else {
441 SLOGE("Cannot get size of block device %s\n", real_blkdev);
442 }
443 close(fd);
444 } else {
445 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
446 cached_off = 0;
447 cached_data = 1;
448 }
449 }
450
451 if (cached_data) {
452 if (metadata_fname) {
453 *metadata_fname = cached_metadata_fname;
454 }
455 if (off) {
456 *off = cached_off;
457 }
458 rc = 0;
459 }
460
461 return rc;
462}
463
Ken Sumralle8744072011-01-18 22:01:55 -0800464/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800465 * update the failed mount count but not change the key.
466 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700467static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800468{
469 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800470 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700471 /* starting_off is set to the SEEK_SET offset
472 * where the crypto structure starts
473 */
474 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800475 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700476 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700477 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800478
Ken Sumrall160b4d62013-04-22 12:15:39 -0700479 if (get_crypt_ftr_info(&fname, &starting_off)) {
480 SLOGE("Unable to get crypt_ftr_info\n");
481 return -1;
482 }
483 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700484 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700485 return -1;
486 }
Ken Sumralle550f782013-08-20 13:48:23 -0700487 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
488 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700489 return -1;
490 }
491
492 /* Seek to the start of the crypt footer */
493 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
494 SLOGE("Cannot seek to real block device footer\n");
495 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800496 }
497
498 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
499 SLOGE("Cannot write real block device footer\n");
500 goto errout;
501 }
502
Ken Sumrall3be890f2011-09-14 16:53:46 -0700503 fstat(fd, &statbuf);
504 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700505 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700506 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800507 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800508 goto errout;
509 }
510 }
511
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800512 /* Success! */
513 rc = 0;
514
515errout:
516 close(fd);
517 return rc;
518
519}
520
Ken Sumrall160b4d62013-04-22 12:15:39 -0700521static inline int unix_read(int fd, void* buff, int len)
522{
523 return TEMP_FAILURE_RETRY(read(fd, buff, len));
524}
525
526static inline int unix_write(int fd, const void* buff, int len)
527{
528 return TEMP_FAILURE_RETRY(write(fd, buff, len));
529}
530
531static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
532{
533 memset(pdata, 0, len);
534 pdata->persist_magic = PERSIST_DATA_MAGIC;
535 pdata->persist_valid_entries = 0;
536}
537
538/* A routine to update the passed in crypt_ftr to the lastest version.
539 * fd is open read/write on the device that holds the crypto footer and persistent
540 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
541 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
542 */
543static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
544{
Kenny Root7434b312013-06-14 11:29:53 -0700545 int orig_major = crypt_ftr->major_version;
546 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700547
Kenny Root7434b312013-06-14 11:29:53 -0700548 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
549 struct crypt_persist_data *pdata;
550 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700551
Kenny Rootc4c70f12013-06-14 12:11:38 -0700552 SLOGW("upgrading crypto footer to 1.1");
553
Kenny Root7434b312013-06-14 11:29:53 -0700554 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
555 if (pdata == NULL) {
556 SLOGE("Cannot allocate persisent data\n");
557 return;
558 }
559 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
560
561 /* Need to initialize the persistent data area */
562 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
563 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100564 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700565 return;
566 }
567 /* Write all zeros to the first copy, making it invalid */
568 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
569
570 /* Write a valid but empty structure to the second copy */
571 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
572 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
573
574 /* Update the footer */
575 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
576 crypt_ftr->persist_data_offset[0] = pdata_offset;
577 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
578 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100579 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700580 }
581
Paul Lawrencef4faa572014-01-29 13:31:03 -0800582 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700583 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800584 /* But keep the old kdf_type.
585 * It will get updated later to KDF_SCRYPT after the password has been verified.
586 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700587 crypt_ftr->kdf_type = KDF_PBKDF2;
588 get_device_scrypt_params(crypt_ftr);
589 crypt_ftr->minor_version = 2;
590 }
591
Paul Lawrencef4faa572014-01-29 13:31:03 -0800592 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
593 SLOGW("upgrading crypto footer to 1.3");
594 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
595 crypt_ftr->minor_version = 3;
596 }
597
Kenny Root7434b312013-06-14 11:29:53 -0700598 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
599 if (lseek64(fd, offset, SEEK_SET) == -1) {
600 SLOGE("Cannot seek to crypt footer\n");
601 return;
602 }
603 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700604 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700605}
606
607
608static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800609{
610 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800611 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700612 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800613 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700614 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700615 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800616
Ken Sumrall160b4d62013-04-22 12:15:39 -0700617 if (get_crypt_ftr_info(&fname, &starting_off)) {
618 SLOGE("Unable to get crypt_ftr_info\n");
619 return -1;
620 }
621 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700622 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700623 return -1;
624 }
625 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700626 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700627 return -1;
628 }
629
630 /* Make sure it's 16 Kbytes in length */
631 fstat(fd, &statbuf);
632 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
633 SLOGE("footer file %s is not the expected size!\n", fname);
634 goto errout;
635 }
636
637 /* Seek to the start of the crypt footer */
638 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
639 SLOGE("Cannot seek to real block device footer\n");
640 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800641 }
642
643 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
644 SLOGE("Cannot read real block device footer\n");
645 goto errout;
646 }
647
648 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700649 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800650 goto errout;
651 }
652
Kenny Rootc96a5f82013-06-14 12:08:28 -0700653 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
654 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
655 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800656 goto errout;
657 }
658
Kenny Rootc96a5f82013-06-14 12:08:28 -0700659 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
660 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
661 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800662 }
663
Ken Sumrall160b4d62013-04-22 12:15:39 -0700664 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
665 * copy on disk before returning.
666 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700667 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700668 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800669 }
670
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800671 /* Success! */
672 rc = 0;
673
674errout:
675 close(fd);
676 return rc;
677}
678
Ken Sumrall160b4d62013-04-22 12:15:39 -0700679static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
680{
681 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
682 crypt_ftr->persist_data_offset[1]) {
683 SLOGE("Crypt_ftr persist data regions overlap");
684 return -1;
685 }
686
687 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
688 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
689 return -1;
690 }
691
692 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
693 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
694 CRYPT_FOOTER_OFFSET) {
695 SLOGE("Persistent data extends past crypto footer");
696 return -1;
697 }
698
699 return 0;
700}
701
702static int load_persistent_data(void)
703{
704 struct crypt_mnt_ftr crypt_ftr;
705 struct crypt_persist_data *pdata = NULL;
706 char encrypted_state[PROPERTY_VALUE_MAX];
707 char *fname;
708 int found = 0;
709 int fd;
710 int ret;
711 int i;
712
713 if (persist_data) {
714 /* Nothing to do, we've already loaded or initialized it */
715 return 0;
716 }
717
718
719 /* If not encrypted, just allocate an empty table and initialize it */
720 property_get("ro.crypto.state", encrypted_state, "");
721 if (strcmp(encrypted_state, "encrypted") ) {
722 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
723 if (pdata) {
724 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
725 persist_data = pdata;
726 return 0;
727 }
728 return -1;
729 }
730
731 if(get_crypt_ftr_and_key(&crypt_ftr)) {
732 return -1;
733 }
734
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700735 if ((crypt_ftr.major_version < 1)
736 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700737 SLOGE("Crypt_ftr version doesn't support persistent data");
738 return -1;
739 }
740
741 if (get_crypt_ftr_info(&fname, NULL)) {
742 return -1;
743 }
744
745 ret = validate_persistent_data_storage(&crypt_ftr);
746 if (ret) {
747 return -1;
748 }
749
750 fd = open(fname, O_RDONLY);
751 if (fd < 0) {
752 SLOGE("Cannot open %s metadata file", fname);
753 return -1;
754 }
755
756 if (persist_data == NULL) {
757 pdata = malloc(crypt_ftr.persist_data_size);
758 if (pdata == NULL) {
759 SLOGE("Cannot allocate memory for persistent data");
760 goto err;
761 }
762 }
763
764 for (i = 0; i < 2; i++) {
765 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
766 SLOGE("Cannot seek to read persistent data on %s", fname);
767 goto err2;
768 }
769 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
770 SLOGE("Error reading persistent data on iteration %d", i);
771 goto err2;
772 }
773 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
774 found = 1;
775 break;
776 }
777 }
778
779 if (!found) {
780 SLOGI("Could not find valid persistent data, creating");
781 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
782 }
783
784 /* Success */
785 persist_data = pdata;
786 close(fd);
787 return 0;
788
789err2:
790 free(pdata);
791
792err:
793 close(fd);
794 return -1;
795}
796
797static int save_persistent_data(void)
798{
799 struct crypt_mnt_ftr crypt_ftr;
800 struct crypt_persist_data *pdata;
801 char *fname;
802 off64_t write_offset;
803 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700804 int fd;
805 int ret;
806
807 if (persist_data == NULL) {
808 SLOGE("No persistent data to save");
809 return -1;
810 }
811
812 if(get_crypt_ftr_and_key(&crypt_ftr)) {
813 return -1;
814 }
815
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700816 if ((crypt_ftr.major_version < 1)
817 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700818 SLOGE("Crypt_ftr version doesn't support persistent data");
819 return -1;
820 }
821
822 ret = validate_persistent_data_storage(&crypt_ftr);
823 if (ret) {
824 return -1;
825 }
826
827 if (get_crypt_ftr_info(&fname, NULL)) {
828 return -1;
829 }
830
831 fd = open(fname, O_RDWR);
832 if (fd < 0) {
833 SLOGE("Cannot open %s metadata file", fname);
834 return -1;
835 }
836
837 pdata = malloc(crypt_ftr.persist_data_size);
838 if (pdata == NULL) {
839 SLOGE("Cannot allocate persistant data");
840 goto err;
841 }
842
843 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
844 SLOGE("Cannot seek to read persistent data on %s", fname);
845 goto err2;
846 }
847
848 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
849 SLOGE("Error reading persistent data before save");
850 goto err2;
851 }
852
853 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
854 /* The first copy is the curent valid copy, so write to
855 * the second copy and erase this one */
856 write_offset = crypt_ftr.persist_data_offset[1];
857 erase_offset = crypt_ftr.persist_data_offset[0];
858 } else {
859 /* The second copy must be the valid copy, so write to
860 * the first copy, and erase the second */
861 write_offset = crypt_ftr.persist_data_offset[0];
862 erase_offset = crypt_ftr.persist_data_offset[1];
863 }
864
865 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100866 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700867 SLOGE("Cannot seek to write persistent data");
868 goto err2;
869 }
870 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
871 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100872 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700873 SLOGE("Cannot seek to erase previous persistent data");
874 goto err2;
875 }
876 fsync(fd);
877 memset(pdata, 0, crypt_ftr.persist_data_size);
878 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
879 (int) crypt_ftr.persist_data_size) {
880 SLOGE("Cannot write to erase previous persistent data");
881 goto err2;
882 }
883 fsync(fd);
884 } else {
885 SLOGE("Cannot write to save persistent data");
886 goto err2;
887 }
888
889 /* Success */
890 free(pdata);
891 close(fd);
892 return 0;
893
894err2:
895 free(pdata);
896err:
897 close(fd);
898 return -1;
899}
900
Paul Lawrencef4faa572014-01-29 13:31:03 -0800901static int hexdigit (char c)
902{
903 if (c >= '0' && c <= '9') return c - '0';
904 c = tolower(c);
905 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
906 return -1;
907}
908
909static unsigned char* convert_hex_ascii_to_key(const char* master_key_ascii,
910 unsigned int* out_keysize)
911{
912 unsigned int i;
913 *out_keysize = 0;
914
915 size_t size = strlen (master_key_ascii);
916 if (size % 2) {
917 SLOGE("Trying to convert ascii string of odd length");
918 return NULL;
919 }
920
921 unsigned char* master_key = (unsigned char*) malloc(size / 2);
922 if (master_key == 0) {
923 SLOGE("Cannot allocate");
924 return NULL;
925 }
926
927 for (i = 0; i < size; i += 2) {
928 int high_nibble = hexdigit (master_key_ascii[i]);
929 int low_nibble = hexdigit (master_key_ascii[i + 1]);
930
931 if(high_nibble < 0 || low_nibble < 0) {
932 SLOGE("Invalid hex string");
933 free (master_key);
934 return NULL;
935 }
936
937 master_key[*out_keysize] = high_nibble * 16 + low_nibble;
938 (*out_keysize)++;
939 }
940
941 return master_key;
942}
943
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800944/* Convert a binary key of specified length into an ascii hex string equivalent,
945 * without the leading 0x and with null termination
946 */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800947static void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800948 char *master_key_ascii)
949{
950 unsigned int i, a;
951 unsigned char nibble;
952
953 for (i=0, a=0; i<keysize; i++, a+=2) {
954 /* For each byte, write out two ascii hex digits */
955 nibble = (master_key[i] >> 4) & 0xf;
956 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
957
958 nibble = master_key[i] & 0xf;
959 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
960 }
961
962 /* Add the null termination */
963 master_key_ascii[a] = '\0';
964
965}
966
Ken Sumralldb5e0262013-02-05 17:39:48 -0800967static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
968 char *real_blk_name, const char *name, int fd,
969 char *extra_params)
970{
Dan Albertc07fa3f2014-12-18 10:00:55 -0800971 _Alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800972 struct dm_ioctl *io;
973 struct dm_target_spec *tgt;
974 char *crypt_params;
975 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
976 int i;
977
978 io = (struct dm_ioctl *) buffer;
979
980 /* Load the mapping table for this device */
981 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
982
983 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
984 io->target_count = 1;
985 tgt->status = 0;
986 tgt->sector_start = 0;
987 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -0700988#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -0800989 if (!strcmp((char *)crypt_ftr->crypto_type_name, "aes-xts")) {
990 strlcpy(tgt->target_type, "req-crypt", DM_MAX_TYPE_NAME);
991 }
992 else {
993 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
994 }
Ajay Dudani87701e22014-09-17 21:02:52 -0700995#else
996 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
997#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -0800998
999 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
1000 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1001 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
1002 master_key_ascii, real_blk_name, extra_params);
1003 crypt_params += strlen(crypt_params) + 1;
1004 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1005 tgt->next = crypt_params - buffer;
1006
1007 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1008 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
1009 break;
1010 }
1011 usleep(500000);
1012 }
1013
1014 if (i == TABLE_LOAD_RETRIES) {
1015 /* We failed to load the table, return an error */
1016 return -1;
1017 } else {
1018 return i + 1;
1019 }
1020}
1021
1022
1023static int get_dm_crypt_version(int fd, const char *name, int *version)
1024{
1025 char buffer[DM_CRYPT_BUF_SIZE];
1026 struct dm_ioctl *io;
1027 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001028
1029 io = (struct dm_ioctl *) buffer;
1030
1031 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1032
1033 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1034 return -1;
1035 }
1036
1037 /* Iterate over the returned versions, looking for name of "crypt".
1038 * When found, get and return the version.
1039 */
1040 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1041 while (v->next) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001042#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001043 if (! strcmp(v->name, "crypt") || ! strcmp(v->name, "req-crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001044#else
Ken Sumralldb5e0262013-02-05 17:39:48 -08001045 if (! strcmp(v->name, "crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001046#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001047 /* We found the crypt driver, return the version, and get out */
1048 version[0] = v->version[0];
1049 version[1] = v->version[1];
1050 version[2] = v->version[2];
1051 return 0;
1052 }
1053 v = (struct dm_target_versions *)(((char *)v) + v->next);
1054 }
1055
1056 return -1;
1057}
1058
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001059static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -07001060 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001061{
1062 char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001063 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001064 unsigned int minor;
Ajay Dudani87701e22014-09-17 21:02:52 -07001065 int fd=0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001066 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001067 int version[3];
1068 char *extra_params;
1069 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001070
1071 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1072 SLOGE("Cannot open device-mapper\n");
1073 goto errout;
1074 }
1075
1076 io = (struct dm_ioctl *) buffer;
1077
1078 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1079 if (ioctl(fd, DM_DEV_CREATE, io)) {
1080 SLOGE("Cannot create dm-crypt device\n");
1081 goto errout;
1082 }
1083
1084 /* Get the device status, in particular, the name of it's device file */
1085 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1086 if (ioctl(fd, DM_DEV_STATUS, io)) {
1087 SLOGE("Cannot retrieve dm-crypt device status\n");
1088 goto errout;
1089 }
1090 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1091 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1092
Ken Sumralldb5e0262013-02-05 17:39:48 -08001093 extra_params = "";
1094 if (! get_dm_crypt_version(fd, name, version)) {
1095 /* Support for allow_discards was added in version 1.11.0 */
1096 if ((version[0] >= 2) ||
1097 ((version[0] == 1) && (version[1] >= 11))) {
1098 extra_params = "1 allow_discards";
1099 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1100 }
Ken Sumralle919efe2012-09-29 17:07:41 -07001101 }
1102
Ken Sumralldb5e0262013-02-05 17:39:48 -08001103 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1104 fd, extra_params);
1105 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001106 SLOGE("Cannot load dm-crypt mapping table.\n");
1107 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001108 } else if (load_count > 1) {
1109 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001110 }
1111
1112 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -08001113 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001114
1115 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1116 SLOGE("Cannot resume the dm-crypt device\n");
1117 goto errout;
1118 }
1119
1120 /* We made it here with no errors. Woot! */
1121 retval = 0;
1122
1123errout:
1124 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1125
1126 return retval;
1127}
1128
Ken Sumrall29d8da82011-05-18 17:20:07 -07001129static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001130{
1131 int fd;
1132 char buffer[DM_CRYPT_BUF_SIZE];
1133 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001134 int retval = -1;
1135
1136 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1137 SLOGE("Cannot open device-mapper\n");
1138 goto errout;
1139 }
1140
1141 io = (struct dm_ioctl *) buffer;
1142
1143 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1144 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1145 SLOGE("Cannot remove dm-crypt device\n");
1146 goto errout;
1147 }
1148
1149 /* We made it here with no errors. Woot! */
1150 retval = 0;
1151
1152errout:
1153 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1154
1155 return retval;
1156
1157}
1158
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001159static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001160 unsigned char *ikey, void *params UNUSED)
1161{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001162 SLOGI("Using pbkdf2 for cryptfs KDF");
1163
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001164 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001165 unsigned int keysize;
1166 char* master_key = (char*)convert_hex_ascii_to_key(passwd, &keysize);
1167 if (!master_key) return -1;
1168 PKCS5_PBKDF2_HMAC_SHA1(master_key, keysize, salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001169 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001170
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001171 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001172 free (master_key);
1173 return 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001174}
1175
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001176static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001177 unsigned char *ikey, void *params)
1178{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001179 SLOGI("Using scrypt for cryptfs KDF");
1180
Kenny Rootc4c70f12013-06-14 12:11:38 -07001181 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1182
1183 int N = 1 << ftr->N_factor;
1184 int r = 1 << ftr->r_factor;
1185 int p = 1 << ftr->p_factor;
1186
1187 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001188 unsigned int keysize;
1189 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &keysize);
1190 if (!master_key) return -1;
1191 crypto_scrypt(master_key, keysize, salt, SALT_LEN, N, r, p, ikey,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001192 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001193
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001194 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001195 free (master_key);
1196 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001197}
1198
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001199static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1200 unsigned char *ikey, void *params)
1201{
1202 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1203
1204 int rc;
1205 unsigned int key_size;
1206 size_t signature_size;
1207 unsigned char* signature;
1208 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1209
1210 int N = 1 << ftr->N_factor;
1211 int r = 1 << ftr->r_factor;
1212 int p = 1 << ftr->p_factor;
1213
1214 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &key_size);
1215 if (!master_key) {
1216 SLOGE("Failed to convert passwd from hex");
1217 return -1;
1218 }
1219
1220 rc = crypto_scrypt(master_key, key_size, salt, SALT_LEN,
1221 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1222 memset(master_key, 0, key_size);
1223 free(master_key);
1224
1225 if (rc) {
1226 SLOGE("scrypt failed");
1227 return -1;
1228 }
1229
Shawn Willdene17a9c42014-09-08 13:04:08 -06001230 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1231 &signature, &signature_size)) {
1232 SLOGE("Signing failed");
1233 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001234 }
1235
1236 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1237 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1238 free(signature);
1239
1240 if (rc) {
1241 SLOGE("scrypt failed");
1242 return -1;
1243 }
1244
1245 return 0;
1246}
1247
1248static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1249 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001250 unsigned char *encrypted_master_key,
1251 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001252{
1253 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1254 EVP_CIPHER_CTX e_ctx;
1255 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001256 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001257
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001258 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001259 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001260
1261 switch (crypt_ftr->kdf_type) {
1262 case KDF_SCRYPT_KEYMASTER:
1263 if (keymaster_create_key(crypt_ftr)) {
1264 SLOGE("keymaster_create_key failed");
1265 return -1;
1266 }
1267
1268 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1269 SLOGE("scrypt failed");
1270 return -1;
1271 }
1272 break;
1273
1274 case KDF_SCRYPT:
1275 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1276 SLOGE("scrypt failed");
1277 return -1;
1278 }
1279 break;
1280
1281 default:
1282 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001283 return -1;
1284 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001285
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001286 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001287 EVP_CIPHER_CTX_init(&e_ctx);
1288 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001289 SLOGE("EVP_EncryptInit failed\n");
1290 return -1;
1291 }
1292 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001293
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001294 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001295 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
1296 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001297 SLOGE("EVP_EncryptUpdate failed\n");
1298 return -1;
1299 }
Adam Langley889c4f12014-09-03 14:23:13 -07001300 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001301 SLOGE("EVP_EncryptFinal failed\n");
1302 return -1;
1303 }
1304
1305 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1306 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1307 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001308 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001309
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001310 /* Store the scrypt of the intermediate key, so we can validate if it's a
1311 password error or mount error when things go wrong.
1312 Note there's no need to check for errors, since if this is incorrect, we
1313 simply won't wipe userdata, which is the correct default behavior
1314 */
1315 int N = 1 << crypt_ftr->N_factor;
1316 int r = 1 << crypt_ftr->r_factor;
1317 int p = 1 << crypt_ftr->p_factor;
1318
1319 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1320 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1321 crypt_ftr->scrypted_intermediate_key,
1322 sizeof(crypt_ftr->scrypted_intermediate_key));
1323
1324 if (rc) {
1325 SLOGE("encrypt_master_key: crypto_scrypt failed");
1326 }
1327
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001328 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001329}
1330
JP Abgrall7bdfa522013-11-15 13:42:56 -08001331static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001332 unsigned char *encrypted_master_key,
1333 unsigned char *decrypted_master_key,
1334 kdf_func kdf, void *kdf_params,
1335 unsigned char** intermediate_key,
1336 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001337{
1338 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001339 EVP_CIPHER_CTX d_ctx;
1340 int decrypted_len, final_len;
1341
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001342 /* Turn the password into an intermediate key and IV that can decrypt the
1343 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001344 if (kdf(passwd, salt, ikey, kdf_params)) {
1345 SLOGE("kdf failed");
1346 return -1;
1347 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001348
1349 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001350 EVP_CIPHER_CTX_init(&d_ctx);
1351 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001352 return -1;
1353 }
1354 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1355 /* Decrypt the master key */
1356 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1357 encrypted_master_key, KEY_LEN_BYTES)) {
1358 return -1;
1359 }
Adam Langley889c4f12014-09-03 14:23:13 -07001360 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001361 return -1;
1362 }
1363
1364 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1365 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001366 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001367
1368 /* Copy intermediate key if needed by params */
1369 if (intermediate_key && intermediate_key_size) {
1370 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1371 if (intermediate_key) {
1372 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1373 *intermediate_key_size = KEY_LEN_BYTES;
1374 }
1375 }
1376
1377 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001378}
1379
Kenny Rootc4c70f12013-06-14 12:11:38 -07001380static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001381{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001382 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001383 *kdf = scrypt_keymaster;
1384 *kdf_params = ftr;
1385 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001386 *kdf = scrypt;
1387 *kdf_params = ftr;
1388 } else {
1389 *kdf = pbkdf2;
1390 *kdf_params = NULL;
1391 }
1392}
1393
JP Abgrall7bdfa522013-11-15 13:42:56 -08001394static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001395 struct crypt_mnt_ftr *crypt_ftr,
1396 unsigned char** intermediate_key,
1397 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001398{
1399 kdf_func kdf;
1400 void *kdf_params;
1401 int ret;
1402
1403 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001404 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1405 decrypted_master_key, kdf, kdf_params,
1406 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001407 if (ret != 0) {
1408 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001409 }
1410
1411 return ret;
1412}
1413
1414static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1415 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001416 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001417 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001418
1419 /* Get some random bits for a key */
1420 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001421 read(fd, key_buf, sizeof(key_buf));
1422 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001423 close(fd);
1424
1425 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001426 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001427}
1428
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001429static int wait_and_unmount(char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001430{
Greg Hackmann955653e2014-09-24 14:55:20 -07001431 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001432#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001433
1434 /* Now umount the tmpfs filesystem */
1435 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001436 if (umount(mountpoint) == 0) {
1437 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001438 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001439
1440 if (errno == EINVAL) {
1441 /* EINVAL is returned if the directory is not a mountpoint,
1442 * i.e. there is no filesystem mounted there. So just get out.
1443 */
1444 break;
1445 }
1446
1447 err = errno;
1448
1449 /* If allowed, be increasingly aggressive before the last two retries */
1450 if (kill) {
1451 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1452 SLOGW("sending SIGHUP to processes with open files\n");
1453 vold_killProcessesWithOpenFiles(mountpoint, 1);
1454 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1455 SLOGW("sending SIGKILL to processes with open files\n");
1456 vold_killProcessesWithOpenFiles(mountpoint, 2);
1457 }
1458 }
1459
1460 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001461 }
1462
1463 if (i < WAIT_UNMOUNT_COUNT) {
1464 SLOGD("unmounting %s succeeded\n", mountpoint);
1465 rc = 0;
1466 } else {
jessica_yu3f14fe42014-09-22 15:57:40 +08001467 vold_killProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001468 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001469 rc = -1;
1470 }
1471
1472 return rc;
1473}
1474
Ken Sumrallc5872692013-05-14 15:26:31 -07001475#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001476static int prep_data_fs(void)
1477{
1478 int i;
1479
1480 /* Do the prep of the /data filesystem */
1481 property_set("vold.post_fs_data_done", "0");
1482 property_set("vold.decrypt", "trigger_post_fs_data");
1483 SLOGD("Just triggered post_fs_data\n");
1484
Ken Sumrallc5872692013-05-14 15:26:31 -07001485 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001486 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001487 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001488
1489 property_get("vold.post_fs_data_done", p, "0");
1490 if (*p == '1') {
1491 break;
1492 } else {
1493 usleep(250000);
1494 }
1495 }
1496 if (i == DATA_PREP_TIMEOUT) {
1497 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001498 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001499 return -1;
1500 } else {
1501 SLOGD("post_fs_data done\n");
1502 return 0;
1503 }
1504}
1505
Paul Lawrence74f29f12014-08-28 15:54:10 -07001506static void cryptfs_set_corrupt()
1507{
1508 // Mark the footer as bad
1509 struct crypt_mnt_ftr crypt_ftr;
1510 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1511 SLOGE("Failed to get crypto footer - panic");
1512 return;
1513 }
1514
1515 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1516 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1517 SLOGE("Failed to set crypto footer - panic");
1518 return;
1519 }
1520}
1521
1522static void cryptfs_trigger_restart_min_framework()
1523{
1524 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1525 SLOGE("Failed to mount tmpfs on data - panic");
1526 return;
1527 }
1528
1529 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1530 SLOGE("Failed to trigger post fs data - panic");
1531 return;
1532 }
1533
1534 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1535 SLOGE("Failed to trigger restart min framework - panic");
1536 return;
1537 }
1538}
1539
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001540/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001541static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001542{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001543 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001544 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001545 static int restart_successful = 0;
1546
1547 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001548 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001549 SLOGE("Encrypted filesystem not validated, aborting");
1550 return -1;
1551 }
1552
1553 if (restart_successful) {
1554 SLOGE("System already restarted with encrypted disk, aborting");
1555 return -1;
1556 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001557
Paul Lawrencef4faa572014-01-29 13:31:03 -08001558 if (restart_main) {
1559 /* Here is where we shut down the framework. The init scripts
1560 * start all services in one of three classes: core, main or late_start.
1561 * On boot, we start core and main. Now, we stop main, but not core,
1562 * as core includes vold and a few other really important things that
1563 * we need to keep running. Once main has stopped, we should be able
1564 * to umount the tmpfs /data, then mount the encrypted /data.
1565 * We then restart the class main, and also the class late_start.
1566 * At the moment, I've only put a few things in late_start that I know
1567 * are not needed to bring up the framework, and that also cause problems
1568 * with unmounting the tmpfs /data, but I hope to add add more services
1569 * to the late_start class as we optimize this to decrease the delay
1570 * till the user is asked for the password to the filesystem.
1571 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001572
Paul Lawrencef4faa572014-01-29 13:31:03 -08001573 /* The init files are setup to stop the class main when vold.decrypt is
1574 * set to trigger_reset_main.
1575 */
1576 property_set("vold.decrypt", "trigger_reset_main");
1577 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001578
Paul Lawrencef4faa572014-01-29 13:31:03 -08001579 /* Ugh, shutting down the framework is not synchronous, so until it
1580 * can be fixed, this horrible hack will wait a moment for it all to
1581 * shut down before proceeding. Without it, some devices cannot
1582 * restart the graphics services.
1583 */
1584 sleep(2);
1585 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001586
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001587 /* Now that the framework is shutdown, we should be able to umount()
1588 * the tmpfs filesystem, and mount the real one.
1589 */
1590
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001591 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1592 if (strlen(crypto_blkdev) == 0) {
1593 SLOGE("fs_crypto_blkdev not set\n");
1594 return -1;
1595 }
1596
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001597 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001598 /* If ro.crypto.readonly is set to 1, mount the decrypted
1599 * filesystem readonly. This is used when /data is mounted by
1600 * recovery mode.
1601 */
1602 char ro_prop[PROPERTY_VALUE_MAX];
1603 property_get("ro.crypto.readonly", ro_prop, "");
1604 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1605 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1606 rec->flags |= MS_RDONLY;
1607 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001608
Ken Sumralle5032c42012-04-01 23:58:44 -07001609 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001610 int retries = RETRY_MOUNT_ATTEMPTS;
1611 int mount_rc;
1612 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1613 crypto_blkdev, 0))
1614 != 0) {
1615 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1616 /* TODO: invoke something similar to
1617 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1618 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1619 SLOGI("Failed to mount %s because it is busy - waiting",
1620 crypto_blkdev);
1621 if (--retries) {
1622 sleep(RETRY_MOUNT_DELAY_SECONDS);
1623 } else {
1624 /* Let's hope that a reboot clears away whatever is keeping
1625 the mount busy */
1626 cryptfs_reboot(reboot);
1627 }
1628 } else {
1629 SLOGE("Failed to mount decrypted data");
1630 cryptfs_set_corrupt();
1631 cryptfs_trigger_restart_min_framework();
1632 SLOGI("Started framework to offer wipe");
1633 return -1;
1634 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001635 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001636
Ken Sumralle5032c42012-04-01 23:58:44 -07001637 property_set("vold.decrypt", "trigger_load_persist_props");
1638 /* Create necessary paths on /data */
1639 if (prep_data_fs()) {
1640 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001641 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001642
1643 /* startup service classes main and late_start */
1644 property_set("vold.decrypt", "trigger_restart_framework");
1645 SLOGD("Just triggered restart_framework\n");
1646
1647 /* Give it a few moments to get started */
1648 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001649 }
1650
Ken Sumrall0cc16632011-01-18 20:32:26 -08001651 if (rc == 0) {
1652 restart_successful = 1;
1653 }
1654
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001655 return rc;
1656}
1657
Paul Lawrencef4faa572014-01-29 13:31:03 -08001658int cryptfs_restart(void)
1659{
Paul Lawrence05335c32015-03-05 09:46:23 -08001660 SLOGI("cryptfs_restart");
1661 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
1662 struct fstab_rec* rec;
1663 int rc;
1664
1665 if (e4crypt_restart(DATA_MNT_POINT)) {
1666 SLOGE("Can't unmount e4crypt temp volume\n");
1667 return -1;
1668 }
1669
1670 rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1671 if (!rec) {
1672 SLOGE("Can't get fstab record for %s\n", DATA_MNT_POINT);
1673 return -1;
1674 }
1675
1676 rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT, rec->blk_device, 0);
1677 if (rc) {
1678 SLOGE("Can't mount %s\n", DATA_MNT_POINT);
1679 return rc;
1680 }
1681
1682 property_set("vold.decrypt", "trigger_restart_framework");
1683 return 0;
1684 }
1685
Paul Lawrencef4faa572014-01-29 13:31:03 -08001686 /* Call internal implementation forcing a restart of main service group */
1687 return cryptfs_restart_internal(1);
1688}
1689
Paul Lawrence05335c32015-03-05 09:46:23 -08001690static int do_crypto_complete(char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001691{
1692 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001693 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001694 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001695
1696 property_get("ro.crypto.state", encrypted_state, "");
1697 if (strcmp(encrypted_state, "encrypted") ) {
1698 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001699 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001700 }
1701
Paul Lawrence05335c32015-03-05 09:46:23 -08001702 if (e4crypt_crypto_complete(mount_point) == 0) {
1703 return CRYPTO_COMPLETE_ENCRYPTED;
1704 }
1705
Ken Sumrall160b4d62013-04-22 12:15:39 -07001706 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001707 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001708
Ken Sumralle1a45852011-12-14 21:24:27 -08001709 /*
1710 * Only report this error if key_loc is a file and it exists.
1711 * If the device was never encrypted, and /data is not mountable for
1712 * some reason, returning 1 should prevent the UI from presenting the
1713 * a "enter password" screen, or worse, a "press button to wipe the
1714 * device" screen.
1715 */
1716 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1717 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001718 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001719 } else {
1720 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001721 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001722 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001723 }
1724
Paul Lawrence74f29f12014-08-28 15:54:10 -07001725 // Test for possible error flags
1726 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1727 SLOGE("Encryption process is partway completed\n");
1728 return CRYPTO_COMPLETE_PARTIAL;
1729 }
1730
1731 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1732 SLOGE("Encryption process was interrupted but cannot continue\n");
1733 return CRYPTO_COMPLETE_INCONSISTENT;
1734 }
1735
1736 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1737 SLOGE("Encryption is successful but data is corrupt\n");
1738 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001739 }
1740
1741 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001742 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001743}
1744
Paul Lawrencef4faa572014-01-29 13:31:03 -08001745static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1746 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001747{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001748 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001749 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001750 char crypto_blkdev[MAXPATHLEN];
1751 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001752 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001753 unsigned int orig_failed_decrypt_count;
1754 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001755 int use_keymaster = 0;
1756 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001757 unsigned char* intermediate_key = 0;
1758 size_t intermediate_key_size = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001759
Paul Lawrencef4faa572014-01-29 13:31:03 -08001760 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1761 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001762
Paul Lawrencef4faa572014-01-29 13:31:03 -08001763 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001764 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1765 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001766 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001767 rc = -1;
1768 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001769 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001770 }
1771
Paul Lawrencef4faa572014-01-29 13:31:03 -08001772 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1773
Ajay Dudani87701e22014-09-17 21:02:52 -07001774#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001775 if (!strcmp((char *)crypt_ftr->crypto_type_name, "aes-xts")) {
1776 if(!set_hw_device_encryption_key(passwd, (char*) crypt_ftr->crypto_type_name)) {
1777 SLOGE("Hardware encryption key does not match");
1778 }
Ajay Dudani87701e22014-09-17 21:02:52 -07001779 }
1780#endif
1781
Paul Lawrence74f29f12014-08-28 15:54:10 -07001782 // Create crypto block device - all (non fatal) code paths
1783 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001784 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1785 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001786 SLOGE("Error creating decrypted block device\n");
1787 rc = -1;
1788 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001789 }
1790
Paul Lawrence74f29f12014-08-28 15:54:10 -07001791 /* Work out if the problem is the password or the data */
1792 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1793 scrypted_intermediate_key)];
1794 int N = 1 << crypt_ftr->N_factor;
1795 int r = 1 << crypt_ftr->r_factor;
1796 int p = 1 << crypt_ftr->p_factor;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001797
Paul Lawrence74f29f12014-08-28 15:54:10 -07001798 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1799 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1800 N, r, p, scrypted_intermediate_key,
1801 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001802
Paul Lawrence74f29f12014-08-28 15:54:10 -07001803 // Does the key match the crypto footer?
1804 if (rc == 0 && memcmp(scrypted_intermediate_key,
1805 crypt_ftr->scrypted_intermediate_key,
1806 sizeof(scrypted_intermediate_key)) == 0) {
1807 SLOGI("Password matches");
1808 rc = 0;
1809 } else {
1810 /* Try mounting the file system anyway, just in case the problem's with
1811 * the footer, not the key. */
1812 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1813 mkdir(tmp_mount_point, 0755);
1814 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1815 SLOGE("Error temp mounting decrypted block device\n");
1816 delete_crypto_blk_dev(label);
1817
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001818 rc = ++crypt_ftr->failed_decrypt_count;
1819 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001820 } else {
1821 /* Success! */
1822 SLOGI("Password did not match but decrypted drive mounted - continue");
1823 umount(tmp_mount_point);
1824 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001825 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001826 }
1827
1828 if (rc == 0) {
1829 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001830 if (orig_failed_decrypt_count != 0) {
1831 put_crypt_ftr_and_key(crypt_ftr);
1832 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001833
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001834 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001835 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001836 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001837
1838 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001839 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001840 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001841 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001842 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001843 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001844 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001845
Paul Lawrence74f29f12014-08-28 15:54:10 -07001846 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001847 use_keymaster = keymaster_check_compatibility();
1848 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001849 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001850 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1851 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1852 upgrade = 1;
1853 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001854 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001855 upgrade = 1;
1856 }
1857
1858 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001859 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1860 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001861 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001862 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001863 }
1864 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001865
1866 // Do not fail even if upgrade failed - machine is bootable
1867 // Note that if this code is ever hit, there is a *serious* problem
1868 // since KDFs should never fail. You *must* fix the kdf before
1869 // proceeding!
1870 if (rc) {
1871 SLOGW("Upgrade failed with error %d,"
1872 " but continuing with previous state",
1873 rc);
1874 rc = 0;
1875 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001876 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001877 }
1878
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001879 errout:
1880 if (intermediate_key) {
1881 memset(intermediate_key, 0, intermediate_key_size);
1882 free(intermediate_key);
1883 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001884 return rc;
1885}
1886
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001887/* Called by vold when it wants to undo the crypto mapping of a volume it
1888 * manages. This is usually in response to a factory reset, when we want
1889 * to undo the crypto mapping so the volume is formatted in the clear.
1890 */
1891int cryptfs_revert_volume(const char *label)
1892{
1893 return delete_crypto_blk_dev((char *)label);
1894}
1895
Ken Sumrall29d8da82011-05-18 17:20:07 -07001896/*
1897 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1898 * Setup a dm-crypt mapping, use the saved master key from
1899 * setting up the /data mapping, and return the new device path.
1900 */
1901int cryptfs_setup_volume(const char *label, int major, int minor,
1902 char *crypto_sys_path, unsigned int max_path,
1903 int *new_major, int *new_minor)
1904{
1905 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1906 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001907 struct stat statbuf;
Tim Murray8439dc92014-12-15 11:56:11 -08001908 unsigned int nr_sec;
1909 int fd;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001910
1911 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1912
Ken Sumrall160b4d62013-04-22 12:15:39 -07001913 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001914
1915 /* Update the fs_size field to be the size of the volume */
1916 fd = open(real_blkdev, O_RDONLY);
1917 nr_sec = get_blkdev_size(fd);
1918 close(fd);
1919 if (nr_sec == 0) {
1920 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1921 return -1;
1922 }
1923
1924 sd_crypt_ftr.fs_size = nr_sec;
1925 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1926 crypto_blkdev, label);
1927
JP Abgrall3334c6a2014-10-10 15:52:11 -07001928 if (stat(crypto_blkdev, &statbuf) < 0) {
1929 SLOGE("Error get stat for crypto_blkdev %s. err=%d(%s)\n",
1930 crypto_blkdev, errno, strerror(errno));
1931 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07001932 *new_major = MAJOR(statbuf.st_rdev);
1933 *new_minor = MINOR(statbuf.st_rdev);
1934
1935 /* Create path to sys entry for this block device */
1936 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1937
1938 return 0;
1939}
1940
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001941int cryptfs_crypto_complete(void)
1942{
1943 return do_crypto_complete("/data");
1944}
1945
Paul Lawrencef4faa572014-01-29 13:31:03 -08001946int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1947{
1948 char encrypted_state[PROPERTY_VALUE_MAX];
1949 property_get("ro.crypto.state", encrypted_state, "");
1950 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1951 SLOGE("encrypted fs already validated or not running with encryption,"
1952 " aborting");
1953 return -1;
1954 }
1955
1956 if (get_crypt_ftr_and_key(crypt_ftr)) {
1957 SLOGE("Error getting crypt footer and key");
1958 return -1;
1959 }
1960
1961 return 0;
1962}
1963
Paul Lawrencefc615042014-10-04 15:32:29 -07001964/*
1965 * TODO - transition patterns to new format in calling code
1966 * and remove this vile hack, and the use of hex in
1967 * the password passing code.
1968 *
1969 * Patterns are passed in zero based (i.e. the top left dot
1970 * is represented by zero, the top middle one etc), but we want
1971 * to store them '1' based.
1972 * This is to allow us to migrate the calling code to use this
1973 * convention. It also solves a nasty problem whereby scrypt ignores
1974 * trailing zeros, so patterns ending at the top left could be
1975 * truncated, and similarly, you could add the top left to any
1976 * pattern and still match.
1977 * adjust_passwd is a hack function that returns the alternate representation
1978 * if the password appears to be a pattern (hex numbers all less than 09)
1979 * If it succeeds we need to try both, and in particular try the alternate
1980 * first. If the original matches, then we need to update the footer
1981 * with the alternate.
1982 * All code that accepts passwords must adjust them first. Since
1983 * cryptfs_check_passwd is always the first function called after a migration
1984 * (and indeed on any boot) we only need to do the double try in this
1985 * function.
1986 */
1987char* adjust_passwd(const char* passwd)
1988{
1989 size_t index, length;
1990
1991 if (!passwd) {
1992 return 0;
1993 }
1994
1995 // Check even length. Hex encoded passwords are always
1996 // an even length, since each character encodes to two characters.
1997 length = strlen(passwd);
1998 if (length % 2) {
1999 SLOGW("Password not correctly hex encoded.");
2000 return 0;
2001 }
2002
2003 // Check password is old-style pattern - a collection of hex
2004 // encoded bytes less than 9 (00 through 08)
2005 for (index = 0; index < length; index +=2) {
2006 if (passwd[index] != '0'
2007 || passwd[index + 1] < '0' || passwd[index + 1] > '8') {
2008 return 0;
2009 }
2010 }
2011
2012 // Allocate room for adjusted passwd and null terminate
2013 char* adjusted = malloc(length + 1);
2014 adjusted[length] = 0;
2015
2016 // Add 0x31 ('1') to each character
2017 for (index = 0; index < length; index += 2) {
2018 // output is 31 through 39 so set first byte to three, second to src + 1
2019 adjusted[index] = '3';
2020 adjusted[index + 1] = passwd[index + 1] + 1;
2021 }
2022
2023 return adjusted;
2024}
2025
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002026int cryptfs_check_passwd(char *passwd)
2027{
Paul Lawrence05335c32015-03-05 09:46:23 -08002028 SLOGI("cryptfs_check_passwd");
2029 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
2030 return e4crypt_check_passwd(DATA_MNT_POINT, passwd);
2031 }
2032
Paul Lawrencef4faa572014-01-29 13:31:03 -08002033 struct crypt_mnt_ftr crypt_ftr;
2034 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002035
Paul Lawrencef4faa572014-01-29 13:31:03 -08002036 rc = check_unmounted_and_get_ftr(&crypt_ftr);
2037 if (rc)
2038 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002039
Paul Lawrencefc615042014-10-04 15:32:29 -07002040 char* adjusted_passwd = adjust_passwd(passwd);
2041 if (adjusted_passwd) {
2042 int failed_decrypt_count = crypt_ftr.failed_decrypt_count;
2043 rc = test_mount_encrypted_fs(&crypt_ftr, adjusted_passwd,
2044 DATA_MNT_POINT, "userdata");
2045
2046 // Maybe the original one still works?
2047 if (rc) {
2048 // Don't double count this failure
2049 crypt_ftr.failed_decrypt_count = failed_decrypt_count;
2050 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
2051 DATA_MNT_POINT, "userdata");
2052 if (!rc) {
2053 // cryptfs_changepw also adjusts so pass original
2054 // Note that adjust_passwd only recognises patterns
2055 // so we can safely use CRYPT_TYPE_PATTERN
2056 SLOGI("Updating pattern to new format");
2057 cryptfs_changepw(CRYPT_TYPE_PATTERN, passwd);
2058 }
2059 }
2060 free(adjusted_passwd);
2061 } else {
2062 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
2063 DATA_MNT_POINT, "userdata");
2064 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002065
2066 if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002067 cryptfs_clear_password();
2068 password = strdup(passwd);
2069 struct timespec now;
2070 clock_gettime(CLOCK_BOOTTIME, &now);
2071 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002072 }
2073
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002074 return rc;
2075}
2076
Ken Sumrall3ad90722011-10-04 20:38:29 -07002077int cryptfs_verify_passwd(char *passwd)
2078{
2079 struct crypt_mnt_ftr crypt_ftr;
2080 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002081 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002082 char encrypted_state[PROPERTY_VALUE_MAX];
2083 int rc;
2084
2085 property_get("ro.crypto.state", encrypted_state, "");
2086 if (strcmp(encrypted_state, "encrypted") ) {
2087 SLOGE("device not encrypted, aborting");
2088 return -2;
2089 }
2090
2091 if (!master_key_saved) {
2092 SLOGE("encrypted fs not yet mounted, aborting");
2093 return -1;
2094 }
2095
2096 if (!saved_mount_point) {
2097 SLOGE("encrypted fs failed to save mount point, aborting");
2098 return -1;
2099 }
2100
Ken Sumrall160b4d62013-04-22 12:15:39 -07002101 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002102 SLOGE("Error getting crypt footer and key\n");
2103 return -1;
2104 }
2105
2106 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2107 /* If the device has no password, then just say the password is valid */
2108 rc = 0;
2109 } else {
Paul Lawrencefc615042014-10-04 15:32:29 -07002110 char* adjusted_passwd = adjust_passwd(passwd);
2111 if (adjusted_passwd) {
2112 passwd = adjusted_passwd;
2113 }
2114
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002115 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002116 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2117 /* They match, the password is correct */
2118 rc = 0;
2119 } else {
2120 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2121 sleep(1);
2122 rc = 1;
2123 }
Paul Lawrencefc615042014-10-04 15:32:29 -07002124
2125 free(adjusted_passwd);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002126 }
2127
2128 return rc;
2129}
2130
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002131/* Initialize a crypt_mnt_ftr structure. The keysize is
2132 * defaulted to 16 bytes, and the filesystem size to 0.
2133 * Presumably, at a minimum, the caller will update the
2134 * filesystem size and crypto_type_name after calling this function.
2135 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002136static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002137{
Ken Sumrall160b4d62013-04-22 12:15:39 -07002138 off64_t off;
2139
2140 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002141 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002142 ftr->major_version = CURRENT_MAJOR_VERSION;
2143 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002144 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06002145 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002146
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002147 switch (keymaster_check_compatibility()) {
2148 case 1:
2149 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2150 break;
2151
2152 case 0:
2153 ftr->kdf_type = KDF_SCRYPT;
2154 break;
2155
2156 default:
2157 SLOGE("keymaster_check_compatibility failed");
2158 return -1;
2159 }
2160
Kenny Rootc4c70f12013-06-14 12:11:38 -07002161 get_device_scrypt_params(ftr);
2162
Ken Sumrall160b4d62013-04-22 12:15:39 -07002163 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2164 if (get_crypt_ftr_info(NULL, &off) == 0) {
2165 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
2166 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
2167 ftr->persist_data_size;
2168 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002169
2170 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002171}
2172
Ken Sumrall29d8da82011-05-18 17:20:07 -07002173static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002174{
Ken Sumralle550f782013-08-20 13:48:23 -07002175 const char *args[10];
2176 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
2177 int num_args;
2178 int status;
2179 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002180 int rc = -1;
2181
Ken Sumrall29d8da82011-05-18 17:20:07 -07002182 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07002183 args[0] = "/system/bin/make_ext4fs";
2184 args[1] = "-a";
2185 args[2] = "/data";
2186 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07002187 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07002188 args[4] = size_str;
2189 args[5] = crypto_blkdev;
2190 num_args = 6;
2191 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
2192 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07002193 } else if (type == F2FS_FS) {
2194 args[0] = "/system/bin/mkfs.f2fs";
2195 args[1] = "-t";
2196 args[2] = "-d1";
2197 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07002198 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07002199 args[4] = size_str;
2200 num_args = 5;
2201 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
2202 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002203 } else {
2204 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
2205 return -1;
2206 }
2207
Ken Sumralle550f782013-08-20 13:48:23 -07002208 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
2209
2210 if (tmp != 0) {
2211 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002212 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07002213 if (WIFEXITED(status)) {
2214 if (WEXITSTATUS(status)) {
2215 SLOGE("Error creating filesystem on %s, exit status %d ",
2216 crypto_blkdev, WEXITSTATUS(status));
2217 } else {
2218 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
2219 rc = 0;
2220 }
2221 } else {
2222 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
2223 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002224 }
2225
2226 return rc;
2227}
2228
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002229#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08002230#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
2231#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002232
2233/* aligned 32K writes tends to make flash happy.
2234 * SD card association recommends it.
2235 */
Ajay Dudani87701e22014-09-17 21:02:52 -07002236#ifndef CONFIG_HW_DISK_ENCRYPTION
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002237#define BLOCKS_AT_A_TIME 8
Ajay Dudani87701e22014-09-17 21:02:52 -07002238#else
2239#define BLOCKS_AT_A_TIME 1024
2240#endif
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002241
2242struct encryptGroupsData
2243{
2244 int realfd;
2245 int cryptofd;
2246 off64_t numblocks;
2247 off64_t one_pct, cur_pct, new_pct;
2248 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002249 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002250 char* real_blkdev, * crypto_blkdev;
2251 int count;
2252 off64_t offset;
2253 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08002254 off64_t last_written_sector;
2255 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002256 time_t time_started;
2257 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002258};
2259
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002260static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002261{
2262 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002263
2264 if (is_used) {
2265 data->used_blocks_already_done++;
2266 }
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002267 if (data->tot_used_blocks) {
2268 data->new_pct = data->used_blocks_already_done / data->one_pct;
2269 } else {
2270 data->new_pct = data->blocks_already_done / data->one_pct;
2271 }
2272
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002273 if (data->new_pct > data->cur_pct) {
2274 char buf[8];
2275 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07002276 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002277 property_set("vold.encrypt_progress", buf);
2278 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002279
2280 if (data->cur_pct >= 5) {
Paul Lawrence9c58a872014-09-30 09:12:51 -07002281 struct timespec time_now;
2282 if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
2283 SLOGW("Error getting time");
2284 } else {
2285 double elapsed_time = difftime(time_now.tv_sec, data->time_started);
2286 off64_t remaining_blocks = data->tot_used_blocks
2287 - data->used_blocks_already_done;
2288 int remaining_time = (int)(elapsed_time * remaining_blocks
2289 / data->used_blocks_already_done);
Paul Lawrence71577502014-08-13 14:55:55 -07002290
Paul Lawrence9c58a872014-09-30 09:12:51 -07002291 // Change time only if not yet set, lower, or a lot higher for
2292 // best user experience
2293 if (data->remaining_time == -1
2294 || remaining_time < data->remaining_time
2295 || remaining_time > data->remaining_time + 60) {
2296 char buf[8];
2297 snprintf(buf, sizeof(buf), "%d", remaining_time);
2298 property_set("vold.encrypt_time_remaining", buf);
2299 data->remaining_time = remaining_time;
2300 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002301 }
2302 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002303}
2304
Paul Lawrence3846be12014-09-22 11:33:54 -07002305static void log_progress(struct encryptGroupsData const* data, bool completed)
2306{
2307 // Precondition - if completed data = 0 else data != 0
2308
2309 // Track progress so we can skip logging blocks
2310 static off64_t offset = -1;
2311
2312 // Need to close existing 'Encrypting from' log?
2313 if (completed || (offset != -1 && data->offset != offset)) {
2314 SLOGI("Encrypted to sector %" PRId64,
2315 offset / info.block_size * CRYPT_SECTOR_SIZE);
2316 offset = -1;
2317 }
2318
2319 // Need to start new 'Encrypting from' log?
2320 if (!completed && offset != data->offset) {
2321 SLOGI("Encrypting from sector %" PRId64,
2322 data->offset / info.block_size * CRYPT_SECTOR_SIZE);
2323 }
2324
2325 // Update offset
2326 if (!completed) {
2327 offset = data->offset + (off64_t)data->count * info.block_size;
2328 }
2329}
2330
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002331static int flush_outstanding_data(struct encryptGroupsData* data)
2332{
2333 if (data->count == 0) {
2334 return 0;
2335 }
2336
Elliott Hughes231bdba2014-06-25 18:36:19 -07002337 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002338
2339 if (pread64(data->realfd, data->buffer,
2340 info.block_size * data->count, data->offset)
2341 <= 0) {
2342 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2343 data->real_blkdev);
2344 return -1;
2345 }
2346
2347 if (pwrite64(data->cryptofd, data->buffer,
2348 info.block_size * data->count, data->offset)
2349 <= 0) {
2350 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2351 data->crypto_blkdev);
2352 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002353 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002354 log_progress(data, false);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002355 }
2356
2357 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002358 data->last_written_sector = (data->offset + data->count)
2359 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002360 return 0;
2361}
2362
2363static int encrypt_groups(struct encryptGroupsData* data)
2364{
2365 unsigned int i;
2366 u8 *block_bitmap = 0;
2367 unsigned int block;
2368 off64_t ret;
2369 int rc = -1;
2370
2371 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
2372 if (!data->buffer) {
2373 SLOGE("Failed to allocate crypto buffer");
2374 goto errout;
2375 }
2376
2377 block_bitmap = malloc(info.block_size);
2378 if (!block_bitmap) {
2379 SLOGE("failed to allocate block bitmap");
2380 goto errout;
2381 }
2382
2383 for (i = 0; i < aux_info.groups; ++i) {
2384 SLOGI("Encrypting group %d", i);
2385
2386 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2387 u32 block_count = min(info.blocks_per_group,
2388 aux_info.len_blocks - first_block);
2389
2390 off64_t offset = (u64)info.block_size
2391 * aux_info.bg_desc[i].bg_block_bitmap;
2392
2393 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2394 if (ret != (int)info.block_size) {
2395 SLOGE("failed to read all of block group bitmap %d", i);
2396 goto errout;
2397 }
2398
2399 offset = (u64)info.block_size * first_block;
2400
2401 data->count = 0;
2402
2403 for (block = 0; block < block_count; block++) {
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002404 int used = bitmap_get_bit(block_bitmap, block);
2405 update_progress(data, used);
2406 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002407 if (data->count == 0) {
2408 data->offset = offset;
2409 }
2410 data->count++;
2411 } else {
2412 if (flush_outstanding_data(data)) {
2413 goto errout;
2414 }
2415 }
2416
2417 offset += info.block_size;
2418
2419 /* Write data if we are aligned or buffer size reached */
2420 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2421 || data->count == BLOCKS_AT_A_TIME) {
2422 if (flush_outstanding_data(data)) {
2423 goto errout;
2424 }
2425 }
Paul Lawrence87999172014-02-20 12:21:31 -08002426
Paul Lawrence73d7a022014-06-09 14:10:09 -07002427 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002428 SLOGE("Stopping encryption due to low battery");
2429 rc = 0;
2430 goto errout;
2431 }
2432
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002433 }
2434 if (flush_outstanding_data(data)) {
2435 goto errout;
2436 }
2437 }
2438
Paul Lawrence87999172014-02-20 12:21:31 -08002439 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002440 rc = 0;
2441
2442errout:
Paul Lawrence3846be12014-09-22 11:33:54 -07002443 log_progress(0, true);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002444 free(data->buffer);
2445 free(block_bitmap);
2446 return rc;
2447}
2448
2449static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2450 char *real_blkdev,
2451 off64_t size,
2452 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002453 off64_t tot_size,
2454 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002455{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002456 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002457 struct encryptGroupsData data;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002458 int rc; // Can't initialize without causing warning -Wclobbered
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002459
Paul Lawrence87999172014-02-20 12:21:31 -08002460 if (previously_encrypted_upto > *size_already_done) {
2461 SLOGD("Not fast encrypting since resuming part way through");
2462 return -1;
2463 }
2464
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002465 memset(&data, 0, sizeof(data));
2466 data.real_blkdev = real_blkdev;
2467 data.crypto_blkdev = crypto_blkdev;
2468
2469 if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002470 SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
2471 real_blkdev, errno, strerror(errno));
Paul Lawrence74f29f12014-08-28 15:54:10 -07002472 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002473 goto errout;
2474 }
2475
2476 if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002477 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
JP Abgrall3334c6a2014-10-10 15:52:11 -07002478 crypto_blkdev, errno, strerror(errno));
JP Abgrall7fc1de82014-10-10 18:43:41 -07002479 rc = ENABLE_INPLACE_ERR_DEV;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002480 goto errout;
2481 }
2482
2483 if (setjmp(setjmp_env)) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002484 SLOGE("Reading ext4 extent caused an exception\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002485 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002486 goto errout;
2487 }
2488
2489 if (read_ext(data.realfd, 0) != 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002490 SLOGE("Failed to read ext4 extent\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002491 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002492 goto errout;
2493 }
2494
2495 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2496 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2497 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2498
JP Abgrall7fc1de82014-10-10 18:43:41 -07002499 SLOGI("Encrypting ext4 filesystem in place...");
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002500
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002501 data.tot_used_blocks = data.numblocks;
2502 for (i = 0; i < aux_info.groups; ++i) {
2503 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2504 }
2505
2506 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002507 data.cur_pct = 0;
Paul Lawrence9c58a872014-09-30 09:12:51 -07002508
2509 struct timespec time_started = {0};
2510 if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
2511 SLOGW("Error getting time at start");
2512 // Note - continue anyway - we'll run with 0
2513 }
2514 data.time_started = time_started.tv_sec;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002515 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002516
2517 rc = encrypt_groups(&data);
2518 if (rc) {
2519 SLOGE("Error encrypting groups");
2520 goto errout;
2521 }
2522
Paul Lawrence87999172014-02-20 12:21:31 -08002523 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002524 rc = 0;
2525
2526errout:
2527 close(data.realfd);
2528 close(data.cryptofd);
2529
2530 return rc;
2531}
2532
Paul Lawrence3846be12014-09-22 11:33:54 -07002533static void log_progress_f2fs(u64 block, bool completed)
2534{
2535 // Precondition - if completed data = 0 else data != 0
2536
2537 // Track progress so we can skip logging blocks
2538 static u64 last_block = (u64)-1;
2539
2540 // Need to close existing 'Encrypting from' log?
2541 if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
2542 SLOGI("Encrypted to block %" PRId64, last_block);
2543 last_block = -1;
2544 }
2545
2546 // Need to start new 'Encrypting from' log?
2547 if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
2548 SLOGI("Encrypting from block %" PRId64, block);
2549 }
2550
2551 // Update offset
2552 if (!completed) {
2553 last_block = block;
2554 }
2555}
2556
Daniel Rosenberge82df162014-08-15 22:19:23 +00002557static int encrypt_one_block_f2fs(u64 pos, void *data)
2558{
2559 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2560
2561 priv_dat->blocks_already_done = pos - 1;
2562 update_progress(priv_dat, 1);
2563
2564 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2565
2566 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002567 SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002568 return -1;
2569 }
2570
2571 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002572 SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002573 return -1;
2574 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002575 log_progress_f2fs(pos, false);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002576 }
2577
2578 return 0;
2579}
2580
2581static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2582 char *real_blkdev,
2583 off64_t size,
2584 off64_t *size_already_done,
2585 off64_t tot_size,
2586 off64_t previously_encrypted_upto)
2587{
Daniel Rosenberge82df162014-08-15 22:19:23 +00002588 struct encryptGroupsData data;
2589 struct f2fs_info *f2fs_info = NULL;
JP Abgrall7fc1de82014-10-10 18:43:41 -07002590 int rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002591 if (previously_encrypted_upto > *size_already_done) {
2592 SLOGD("Not fast encrypting since resuming part way through");
JP Abgrall7fc1de82014-10-10 18:43:41 -07002593 return ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002594 }
2595 memset(&data, 0, sizeof(data));
2596 data.real_blkdev = real_blkdev;
2597 data.crypto_blkdev = crypto_blkdev;
2598 data.realfd = -1;
2599 data.cryptofd = -1;
2600 if ( (data.realfd = open64(real_blkdev, O_RDWR)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002601 SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
Daniel Rosenberge82df162014-08-15 22:19:23 +00002602 real_blkdev);
2603 goto errout;
2604 }
2605 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002606 SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
JP Abgrall3334c6a2014-10-10 15:52:11 -07002607 crypto_blkdev, errno, strerror(errno));
JP Abgrall7fc1de82014-10-10 18:43:41 -07002608 rc = ENABLE_INPLACE_ERR_DEV;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002609 goto errout;
2610 }
2611
2612 f2fs_info = generate_f2fs_info(data.realfd);
2613 if (!f2fs_info)
2614 goto errout;
2615
2616 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2617 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2618 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2619
2620 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2621
2622 data.one_pct = data.tot_used_blocks / 100;
2623 data.cur_pct = 0;
2624 data.time_started = time(NULL);
2625 data.remaining_time = -1;
2626
2627 data.buffer = malloc(f2fs_info->block_size);
2628 if (!data.buffer) {
2629 SLOGE("Failed to allocate crypto buffer");
2630 goto errout;
2631 }
2632
2633 data.count = 0;
2634
2635 /* Currently, this either runs to completion, or hits a nonrecoverable error */
2636 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2637
2638 if (rc) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002639 SLOGE("Error in running over f2fs blocks");
2640 rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002641 goto errout;
2642 }
2643
2644 *size_already_done += size;
2645 rc = 0;
2646
2647errout:
2648 if (rc)
2649 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2650
Paul Lawrence3846be12014-09-22 11:33:54 -07002651 log_progress_f2fs(0, true);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002652 free(f2fs_info);
2653 free(data.buffer);
2654 close(data.realfd);
2655 close(data.cryptofd);
2656
2657 return rc;
2658}
2659
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002660static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2661 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002662 off64_t tot_size,
2663 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002664{
2665 int realfd, cryptofd;
2666 char *buf[CRYPT_INPLACE_BUFSIZE];
JP Abgrall7fc1de82014-10-10 18:43:41 -07002667 int rc = ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002668 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002669 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002670 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002671
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002672 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
2673 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002674 return ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002675 }
2676
2677 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002678 SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
2679 crypto_blkdev, errno, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002680 close(realfd);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002681 return ENABLE_INPLACE_ERR_DEV;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002682 }
2683
2684 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2685 * The size passed in is the number of 512 byte sectors in the filesystem.
2686 * So compute the number of whole 4K blocks we should read/write,
2687 * and the remainder.
2688 */
2689 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2690 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002691 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2692 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002693
2694 SLOGE("Encrypting filesystem in place...");
2695
Paul Lawrence87999172014-02-20 12:21:31 -08002696 i = previously_encrypted_upto + 1 - *size_already_done;
2697
2698 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2699 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2700 goto errout;
2701 }
2702
2703 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2704 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2705 goto errout;
2706 }
2707
2708 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2709 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2710 SLOGE("Error reading initial sectors from real_blkdev %s for "
2711 "inplace encrypt\n", crypto_blkdev);
2712 goto errout;
2713 }
2714 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2715 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2716 "inplace encrypt\n", crypto_blkdev);
2717 goto errout;
2718 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002719 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002720 }
2721 }
2722
Ken Sumrall29d8da82011-05-18 17:20:07 -07002723 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002724 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002725 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002726 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002727 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002728 if (new_pct > cur_pct) {
2729 char buf[8];
2730
2731 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002732 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002733 property_set("vold.encrypt_progress", buf);
2734 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002735 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002736 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002737 goto errout;
2738 }
2739 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002740 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2741 goto errout;
2742 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002743 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002744 CRYPT_SECTORS_PER_BUFSIZE,
2745 i * CRYPT_SECTORS_PER_BUFSIZE);
2746 }
2747
Paul Lawrence73d7a022014-06-09 14:10:09 -07002748 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002749 SLOGE("Stopping encryption due to low battery");
2750 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2751 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002752 goto errout;
2753 }
2754 }
2755
2756 /* Do any remaining sectors */
2757 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002758 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2759 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002760 goto errout;
2761 }
Paul Lawrence87999172014-02-20 12:21:31 -08002762 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2763 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002764 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002765 } else {
2766 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002767 }
2768 }
2769
Ken Sumrall29d8da82011-05-18 17:20:07 -07002770 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002771 rc = 0;
2772
2773errout:
2774 close(realfd);
2775 close(cryptofd);
2776
2777 return rc;
2778}
2779
JP Abgrall7fc1de82014-10-10 18:43:41 -07002780/* returns on of the ENABLE_INPLACE_* return codes */
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002781static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2782 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002783 off64_t tot_size,
2784 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002785{
JP Abgrall7fc1de82014-10-10 18:43:41 -07002786 int rc_ext4, rc_f2fs, rc_full;
Paul Lawrence87999172014-02-20 12:21:31 -08002787 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002788 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002789 }
2790
2791 if (*size_already_done + size < previously_encrypted_upto) {
2792 *size_already_done += size;
2793 return 0;
2794 }
2795
Daniel Rosenberge82df162014-08-15 22:19:23 +00002796 /* TODO: identify filesystem type.
2797 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2798 * then we will drop down to cryptfs_enable_inplace_f2fs.
2799 * */
JP Abgrall7fc1de82014-10-10 18:43:41 -07002800 if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002801 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002802 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002803 return 0;
2804 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002805 SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002806
JP Abgrall7fc1de82014-10-10 18:43:41 -07002807 if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002808 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002809 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002810 return 0;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002811 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002812 SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002813
JP Abgrall7fc1de82014-10-10 18:43:41 -07002814 rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002815 size, size_already_done, tot_size,
2816 previously_encrypted_upto);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002817 SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
2818
2819 /* Hack for b/17898962, the following is the symptom... */
2820 if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
2821 && rc_f2fs == ENABLE_INPLACE_ERR_DEV
2822 && rc_full == ENABLE_INPLACE_ERR_DEV) {
2823 return ENABLE_INPLACE_ERR_DEV;
2824 }
2825 return rc_full;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002826}
2827
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002828#define CRYPTO_ENABLE_WIPE 1
2829#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002830
2831#define FRAMEWORK_BOOT_WAIT 60
2832
Ken Sumrall29d8da82011-05-18 17:20:07 -07002833static inline int should_encrypt(struct volume_info *volume)
2834{
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002835 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
Ken Sumrall29d8da82011-05-18 17:20:07 -07002836 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
2837}
2838
Paul Lawrence87999172014-02-20 12:21:31 -08002839static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2840{
2841 int fd = open(filename, O_RDONLY);
2842 if (fd == -1) {
2843 SLOGE("Error opening file %s", filename);
2844 return -1;
2845 }
2846
2847 char block[CRYPT_INPLACE_BUFSIZE];
2848 memset(block, 0, sizeof(block));
2849 if (unix_read(fd, block, sizeof(block)) < 0) {
2850 SLOGE("Error reading file %s", filename);
2851 close(fd);
2852 return -1;
2853 }
2854
2855 close(fd);
2856
2857 SHA256_CTX c;
2858 SHA256_Init(&c);
2859 SHA256_Update(&c, block, sizeof(block));
2860 SHA256_Final(buf, &c);
2861
2862 return 0;
2863}
2864
JP Abgrall62c7af32014-06-16 13:01:23 -07002865static int get_fs_type(struct fstab_rec *rec)
2866{
2867 if (!strcmp(rec->fs_type, "ext4")) {
2868 return EXT4_FS;
2869 } else if (!strcmp(rec->fs_type, "f2fs")) {
2870 return F2FS_FS;
2871 } else {
2872 return -1;
2873 }
2874}
2875
Paul Lawrence87999172014-02-20 12:21:31 -08002876static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2877 char *crypto_blkdev, char *real_blkdev,
2878 int previously_encrypted_upto)
2879{
2880 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002881 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002882
Paul Lawrence73d7a022014-06-09 14:10:09 -07002883 if (!is_battery_ok_to_start()) {
2884 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002885 return 0;
2886 }
2887
2888 /* The size of the userdata partition, and add in the vold volumes below */
2889 tot_encryption_size = crypt_ftr->fs_size;
2890
2891 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002892 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2893 int fs_type = get_fs_type(rec);
2894 if (fs_type < 0) {
2895 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2896 return -1;
2897 }
2898 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002899 } else if (how == CRYPTO_ENABLE_INPLACE) {
2900 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2901 crypt_ftr->fs_size, &cur_encryption_done,
2902 tot_encryption_size,
2903 previously_encrypted_upto);
2904
JP Abgrall7fc1de82014-10-10 18:43:41 -07002905 if (rc == ENABLE_INPLACE_ERR_DEV) {
2906 /* Hack for b/17898962 */
2907 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2908 cryptfs_reboot(reboot);
2909 }
2910
Paul Lawrence73d7a022014-06-09 14:10:09 -07002911 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002912 crypt_ftr->encrypted_upto = cur_encryption_done;
2913 }
2914
Paul Lawrence73d7a022014-06-09 14:10:09 -07002915 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002916 /* The inplace routine never actually sets the progress to 100% due
2917 * to the round down nature of integer division, so set it here */
2918 property_set("vold.encrypt_progress", "100");
2919 }
2920 } else {
2921 /* Shouldn't happen */
2922 SLOGE("cryptfs_enable: internal error, unknown option\n");
2923 rc = -1;
2924 }
2925
2926 return rc;
2927}
2928
Paul Lawrence13486032014-02-03 13:28:11 -08002929int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
2930 int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002931{
2932 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002933 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07002934 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002935 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Tim Murray8439dc92014-12-15 11:56:11 -08002936 int rc=-1, fd, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002937 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002938 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002939 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002940 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002941 char key_loc[PROPERTY_VALUE_MAX];
2942 char fuse_sdcard[PROPERTY_VALUE_MAX];
2943 char *sd_mnt_point;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002944 int num_vols;
2945 struct volume_info *vol_list = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002946 off64_t previously_encrypted_upto = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002947
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002948 if (!strcmp(howarg, "wipe")) {
2949 how = CRYPTO_ENABLE_WIPE;
2950 } else if (! strcmp(howarg, "inplace")) {
2951 how = CRYPTO_ENABLE_INPLACE;
2952 } else {
2953 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002954 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002955 }
2956
Paul Lawrence87999172014-02-20 12:21:31 -08002957 /* See if an encryption was underway and interrupted */
2958 if (how == CRYPTO_ENABLE_INPLACE
2959 && get_crypt_ftr_and_key(&crypt_ftr) == 0
2960 && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
2961 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2962 crypt_ftr.encrypted_upto = 0;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002963 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
2964
2965 /* At this point, we are in an inconsistent state. Until we successfully
2966 complete encryption, a reboot will leave us broken. So mark the
2967 encryption failed in case that happens.
2968 On successfully completing encryption, remove this flag */
2969 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2970
2971 put_crypt_ftr_and_key(&crypt_ftr);
Paul Lawrence87999172014-02-20 12:21:31 -08002972 }
2973
2974 property_get("ro.crypto.state", encrypted_state, "");
2975 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2976 SLOGE("Device is already running encrypted, aborting");
2977 goto error_unencrypted;
2978 }
2979
2980 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2981 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002982 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002983
Ken Sumrall3ed82362011-01-28 23:31:16 -08002984 /* Get the size of the real block device */
2985 fd = open(real_blkdev, O_RDONLY);
2986 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
2987 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2988 goto error_unencrypted;
2989 }
2990 close(fd);
2991
2992 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002993 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002994 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002995 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002996 if (fs_size_sec == 0)
2997 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2998
Paul Lawrence87999172014-02-20 12:21:31 -08002999 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003000
3001 if (fs_size_sec > max_fs_size_sec) {
3002 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
3003 goto error_unencrypted;
3004 }
3005 }
3006
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003007 /* Get a wakelock as this may take a while, and we don't want the
3008 * device to sleep on us. We'll grab a partial wakelock, and if the UI
3009 * wants to keep the screen on, it can grab a full wakelock.
3010 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003011 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003012 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
3013
Jeff Sharkey7382f812012-08-23 14:08:59 -07003014 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07003015 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07003016 if (!sd_mnt_point) {
3017 sd_mnt_point = getenv("EXTERNAL_STORAGE");
3018 }
3019 if (!sd_mnt_point) {
3020 sd_mnt_point = "/mnt/sdcard";
3021 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07003022
Paul Lawrence87999172014-02-20 12:21:31 -08003023 /* TODO
3024 * Currently do not have test devices with multiple encryptable volumes.
3025 * When we acquire some, re-add support.
3026 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003027 num_vols=vold_getNumDirectVolumes();
3028 vol_list = malloc(sizeof(struct volume_info) * num_vols);
3029 vold_getDirectVolumeList(vol_list);
3030
3031 for (i=0; i<num_vols; i++) {
3032 if (should_encrypt(&vol_list[i])) {
Paul Lawrence87999172014-02-20 12:21:31 -08003033 SLOGE("Cannot encrypt if there are multiple encryptable volumes"
3034 "%s\n", vol_list[i].label);
3035 goto error_unencrypted;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003036 }
3037 }
3038
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003039 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003040 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003041 */
3042 property_set("vold.decrypt", "trigger_shutdown_framework");
3043 SLOGD("Just asked init to shut down class main\n");
3044
Ken Sumrall425524d2012-06-14 20:55:28 -07003045 if (vold_unmountAllAsecs()) {
3046 /* Just report the error. If any are left mounted,
3047 * umounting /data below will fail and handle the error.
3048 */
3049 SLOGE("Error unmounting internal asecs");
3050 }
3051
Ken Sumrall29d8da82011-05-18 17:20:07 -07003052 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
3053 if (!strcmp(fuse_sdcard, "true")) {
3054 /* This is a device using the fuse layer to emulate the sdcard semantics
3055 * on top of the userdata partition. vold does not manage it, it is managed
3056 * by the sdcard service. The sdcard service was killed by the property trigger
3057 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
3058 * unlike the case for vold managed devices above.
3059 */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07003060 if (wait_and_unmount(sd_mnt_point, false)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07003061 goto error_shutting_down;
3062 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08003063 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003064
3065 /* Now unmount the /data partition. */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07003066 if (wait_and_unmount(DATA_MNT_POINT, false)) {
JP Abgrall502dc742013-11-01 13:06:20 -07003067 if (allow_reboot) {
3068 goto error_shutting_down;
3069 } else {
3070 goto error_unencrypted;
3071 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003072 }
3073
3074 /* Do extra work for a better UX when doing the long inplace encryption */
3075 if (how == CRYPTO_ENABLE_INPLACE) {
3076 /* Now that /data is unmounted, we need to mount a tmpfs
3077 * /data, set a property saying we're doing inplace encryption,
3078 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003079 */
Ken Sumralle5032c42012-04-01 23:58:44 -07003080 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003081 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003082 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003083 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08003084 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003085
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003086 /* restart the framework. */
3087 /* Create necessary paths on /data */
3088 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003089 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003090 }
3091
Ken Sumrall92736ef2012-10-17 20:57:14 -07003092 /* Ugh, shutting down the framework is not synchronous, so until it
3093 * can be fixed, this horrible hack will wait a moment for it all to
3094 * shut down before proceeding. Without it, some devices cannot
3095 * restart the graphics services.
3096 */
3097 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003098 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003099
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003100 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003101 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence87999172014-02-20 12:21:31 -08003102 if (previously_encrypted_upto == 0) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07003103 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
3104 goto error_shutting_down;
3105 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003106
Paul Lawrence87999172014-02-20 12:21:31 -08003107 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
3108 crypt_ftr.fs_size = nr_sec
3109 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
3110 } else {
3111 crypt_ftr.fs_size = nr_sec;
3112 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07003113 /* At this point, we are in an inconsistent state. Until we successfully
3114 complete encryption, a reboot will leave us broken. So mark the
3115 encryption failed in case that happens.
3116 On successfully completing encryption, remove this flag */
3117 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence87999172014-02-20 12:21:31 -08003118 crypt_ftr.crypt_type = crypt_type;
Ajay Dudani87701e22014-09-17 21:02:52 -07003119#ifndef CONFIG_HW_DISK_ENCRYPTION
3120 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
3121#else
3122 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-xts", MAX_CRYPTO_TYPE_NAME_LEN);
3123
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08003124 rc = clear_hw_device_encryption_key();
Ajay Dudani87701e22014-09-17 21:02:52 -07003125 if (!rc) {
3126 SLOGE("Error clearing device encryption hardware key. rc = %d", rc);
3127 }
3128
3129 rc = set_hw_device_encryption_key(passwd,
3130 (char*) crypt_ftr.crypto_type_name);
3131 if (!rc) {
3132 SLOGE("Error initializing device encryption hardware key. rc = %d", rc);
3133 goto error_shutting_down;
3134 }
3135#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003136
Paul Lawrence87999172014-02-20 12:21:31 -08003137 /* Make an encrypted master key */
3138 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
3139 SLOGE("Cannot create encrypted master key\n");
3140 goto error_shutting_down;
3141 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003142
Paul Lawrence87999172014-02-20 12:21:31 -08003143 /* Write the key to the end of the partition */
3144 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003145
Paul Lawrence87999172014-02-20 12:21:31 -08003146 /* If any persistent data has been remembered, save it.
3147 * If none, create a valid empty table and save that.
3148 */
3149 if (!persist_data) {
3150 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
3151 if (pdata) {
3152 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
3153 persist_data = pdata;
3154 }
3155 }
3156 if (persist_data) {
3157 save_persistent_data();
3158 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003159 }
3160
Ajay Dudani87701e22014-09-17 21:02:52 -07003161 if (how == CRYPTO_ENABLE_INPLACE) {
3162 /* startup service classes main and late_start */
3163 property_set("vold.decrypt", "trigger_restart_min_framework");
3164 SLOGD("Just triggered restart_min_framework\n");
3165
3166 /* OK, the framework is restarted and will soon be showing a
3167 * progress bar. Time to setup an encrypted mapping, and
3168 * either write a new filesystem, or encrypt in place updating
3169 * the progress bar as we work.
3170 */
3171 }
3172
Paul Lawrenced0c7b172014-08-08 14:28:10 -07003173 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07003174 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
3175 "userdata");
3176
Paul Lawrence87999172014-02-20 12:21:31 -08003177 /* If we are continuing, check checksums match */
3178 rc = 0;
3179 if (previously_encrypted_upto) {
3180 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
3181 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07003182
Paul Lawrence87999172014-02-20 12:21:31 -08003183 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
3184 sizeof(hash_first_block)) != 0) {
3185 SLOGE("Checksums do not match - trigger wipe");
3186 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003187 }
3188 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003189
Paul Lawrence87999172014-02-20 12:21:31 -08003190 if (!rc) {
3191 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
3192 crypto_blkdev, real_blkdev,
3193 previously_encrypted_upto);
3194 }
3195
3196 /* Calculate checksum if we are not finished */
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003197 if (!rc && how == CRYPTO_ENABLE_INPLACE
3198 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003199 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
3200 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07003201 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08003202 SLOGE("Error calculating checksum for continuing encryption");
3203 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003204 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003205 }
3206
3207 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003208 delete_crypto_blk_dev("userdata");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003209
3210 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003211
3212 if (! rc) {
3213 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003214 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08003215
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003216 if (how == CRYPTO_ENABLE_INPLACE
3217 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003218 SLOGD("Encrypted up to sector %lld - will continue after reboot",
3219 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07003220 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08003221 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07003222
Paul Lawrence6bfed202014-07-28 12:47:22 -07003223 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08003224
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003225 if (how == CRYPTO_ENABLE_WIPE
3226 || crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003227 char value[PROPERTY_VALUE_MAX];
3228 property_get("ro.crypto.state", value, "");
3229 if (!strcmp(value, "")) {
3230 /* default encryption - continue first boot sequence */
3231 property_set("ro.crypto.state", "encrypted");
3232 release_wake_lock(lockid);
3233 cryptfs_check_passwd(DEFAULT_PASSWORD);
3234 cryptfs_restart_internal(1);
3235 return 0;
3236 } else {
3237 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08003238 cryptfs_reboot(reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003239 }
Paul Lawrence87999172014-02-20 12:21:31 -08003240 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003241 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Paul Lawrence87999172014-02-20 12:21:31 -08003242 cryptfs_reboot(shutdown);
3243 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003244 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003245 char value[PROPERTY_VALUE_MAX];
3246
Ken Sumrall319369a2012-06-27 16:30:18 -07003247 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003248 if (!strcmp(value, "1")) {
3249 /* wipe data if encryption failed */
3250 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
3251 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07003252 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003253 if (fd >= 0) {
Jeff Sharkeydd1a8042014-09-24 11:46:51 -07003254 write(fd, "--wipe_data\n", strlen("--wipe_data\n") + 1);
3255 write(fd, "--reason=cryptfs_enable_internal\n", strlen("--reason=cryptfs_enable_internal\n") + 1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003256 close(fd);
3257 } else {
3258 SLOGE("could not open /cache/recovery/command\n");
3259 }
Paul Lawrence87999172014-02-20 12:21:31 -08003260 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003261 } else {
3262 /* set property to trigger dialog */
3263 property_set("vold.encrypt_progress", "error_partially_encrypted");
3264 release_wake_lock(lockid);
3265 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003266 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003267 }
3268
Ken Sumrall3ed82362011-01-28 23:31:16 -08003269 /* hrm, the encrypt step claims success, but the reboot failed.
3270 * This should not happen.
3271 * Set the property and return. Hope the framework can deal with it.
3272 */
3273 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003274 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003275 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08003276
3277error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07003278 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003279 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003280 if (lockid[0]) {
3281 release_wake_lock(lockid);
3282 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003283 return -1;
3284
3285error_shutting_down:
3286 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3287 * but the framework is stopped and not restarted to show the error, so it's up to
3288 * vold to restart the system.
3289 */
3290 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08003291 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003292
3293 /* shouldn't get here */
3294 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003295 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003296 if (lockid[0]) {
3297 release_wake_lock(lockid);
3298 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003299 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003300}
3301
Paul Lawrence45f10532014-04-04 18:11:56 +00003302int cryptfs_enable(char *howarg, int type, char *passwd, int allow_reboot)
Paul Lawrence13486032014-02-03 13:28:11 -08003303{
Paul Lawrencefc615042014-10-04 15:32:29 -07003304 char* adjusted_passwd = adjust_passwd(passwd);
3305 if (adjusted_passwd) {
3306 passwd = adjusted_passwd;
3307 }
3308
3309 int rc = cryptfs_enable_internal(howarg, type, passwd, allow_reboot);
3310
3311 free(adjusted_passwd);
3312 return rc;
Paul Lawrence13486032014-02-03 13:28:11 -08003313}
3314
3315int cryptfs_enable_default(char *howarg, int allow_reboot)
3316{
3317 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
3318 DEFAULT_PASSWORD, allow_reboot);
3319}
3320
3321int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003322{
Paul Lawrence05335c32015-03-05 09:46:23 -08003323 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3324 return e4crypt_change_password(DATA_MNT_POINT, crypt_type, newpw);
3325 }
3326
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003327 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08003328 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003329
3330 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003331 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003332 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003333 return -1;
3334 }
3335
Paul Lawrencef4faa572014-01-29 13:31:03 -08003336 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3337 SLOGE("Invalid crypt_type %d", crypt_type);
3338 return -1;
3339 }
3340
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003341 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003342 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003343 SLOGE("Error getting crypt footer and key");
3344 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003345 }
3346
Paul Lawrencef4faa572014-01-29 13:31:03 -08003347 crypt_ftr.crypt_type = crypt_type;
3348
Paul Lawrencefc615042014-10-04 15:32:29 -07003349 char* adjusted_passwd = adjust_passwd(newpw);
3350 if (adjusted_passwd) {
3351 newpw = adjusted_passwd;
3352 }
3353
JP Abgrall933216c2015-02-11 13:44:32 -08003354 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08003355 : newpw,
3356 crypt_ftr.salt,
3357 saved_master_key,
3358 crypt_ftr.master_key,
3359 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08003360 free(adjusted_passwd);
3361 if (rc) {
3362 SLOGE("Encrypt master key failed: %d", rc);
3363 return -1;
3364 }
Jason parks70a4b3f2011-01-28 10:10:47 -06003365 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003366 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003367
Ajay Dudani87701e22014-09-17 21:02:52 -07003368#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08003369 if (!strcmp((char *)crypt_ftr.crypto_type_name, "aes-xts")) {
3370 if (crypt_type == CRYPT_TYPE_DEFAULT) {
3371 int rc = update_hw_device_encryption_key(DEFAULT_PASSWORD, (char*) crypt_ftr.crypto_type_name);
3372 SLOGD("Update hardware encryption key to default for crypt_type: %d. rc = %d", crypt_type, rc);
3373 if (!rc)
3374 return -1;
3375 } else {
3376 int rc = update_hw_device_encryption_key(newpw, (char*) crypt_ftr.crypto_type_name);
3377 SLOGD("Update hardware encryption key for crypt_type: %d. rc = %d", crypt_type, rc);
3378 if (!rc)
3379 return -1;
3380 }
Ajay Dudani87701e22014-09-17 21:02:52 -07003381 }
3382#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003383 return 0;
3384}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003385
Rubin Xu85c01f92014-10-13 12:49:54 +01003386static unsigned int persist_get_max_entries(int encrypted) {
3387 struct crypt_mnt_ftr crypt_ftr;
3388 unsigned int dsize;
3389 unsigned int max_persistent_entries;
3390
3391 /* If encrypted, use the values from the crypt_ftr, otherwise
3392 * use the values for the current spec.
3393 */
3394 if (encrypted) {
3395 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3396 return -1;
3397 }
3398 dsize = crypt_ftr.persist_data_size;
3399 } else {
3400 dsize = CRYPT_PERSIST_DATA_SIZE;
3401 }
3402
3403 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3404 sizeof(struct crypt_persist_entry);
3405
3406 return max_persistent_entries;
3407}
3408
3409static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003410{
3411 unsigned int i;
3412
3413 if (persist_data == NULL) {
3414 return -1;
3415 }
3416 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3417 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3418 /* We found it! */
3419 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3420 return 0;
3421 }
3422 }
3423
3424 return -1;
3425}
3426
Rubin Xu85c01f92014-10-13 12:49:54 +01003427static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003428{
3429 unsigned int i;
3430 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003431 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003432
3433 if (persist_data == NULL) {
3434 return -1;
3435 }
3436
Rubin Xu85c01f92014-10-13 12:49:54 +01003437 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003438
3439 num = persist_data->persist_valid_entries;
3440
3441 for (i = 0; i < num; i++) {
3442 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3443 /* We found an existing entry, update it! */
3444 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3445 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3446 return 0;
3447 }
3448 }
3449
3450 /* We didn't find it, add it to the end, if there is room */
3451 if (persist_data->persist_valid_entries < max_persistent_entries) {
3452 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3453 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3454 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3455 persist_data->persist_valid_entries++;
3456 return 0;
3457 }
3458
3459 return -1;
3460}
3461
Rubin Xu85c01f92014-10-13 12:49:54 +01003462/**
3463 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3464 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3465 */
3466static int match_multi_entry(const char *key, const char *field, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003467 unsigned int field_len;
3468 unsigned int key_index;
3469 field_len = strlen(field);
3470
3471 if (index == 0) {
3472 // The first key in a multi-entry field is just the filedname itself.
3473 if (!strcmp(key, field)) {
3474 return 1;
3475 }
3476 }
3477 // Match key against "%s_%d" % (field, index)
3478 if (strlen(key) < field_len + 1 + 1) {
3479 // Need at least a '_' and a digit.
3480 return 0;
3481 }
3482 if (strncmp(key, field, field_len)) {
3483 // If the key does not begin with field, it's not a match.
3484 return 0;
3485 }
3486 if (1 != sscanf(&key[field_len],"_%d", &key_index)) {
3487 return 0;
3488 }
3489 return key_index >= index;
3490}
3491
3492/*
3493 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3494 * remaining entries starting from index will be deleted.
3495 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3496 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3497 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3498 *
3499 */
3500static int persist_del_keys(const char *fieldname, unsigned index)
3501{
3502 unsigned int i;
3503 unsigned int j;
3504 unsigned int num;
3505
3506 if (persist_data == NULL) {
3507 return PERSIST_DEL_KEY_ERROR_OTHER;
3508 }
3509
3510 num = persist_data->persist_valid_entries;
3511
3512 j = 0; // points to the end of non-deleted entries.
3513 // Filter out to-be-deleted entries in place.
3514 for (i = 0; i < num; i++) {
3515 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3516 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3517 j++;
3518 }
3519 }
3520
3521 if (j < num) {
3522 persist_data->persist_valid_entries = j;
3523 // Zeroise the remaining entries
3524 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3525 return PERSIST_DEL_KEY_OK;
3526 } else {
3527 // Did not find an entry matching the given fieldname
3528 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3529 }
3530}
3531
3532static int persist_count_keys(const char *fieldname)
3533{
3534 unsigned int i;
3535 unsigned int count;
3536
3537 if (persist_data == NULL) {
3538 return -1;
3539 }
3540
3541 count = 0;
3542 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3543 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3544 count++;
3545 }
3546 }
3547
3548 return count;
3549}
3550
Ken Sumrall160b4d62013-04-22 12:15:39 -07003551/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003552int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003553{
3554 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003555 /* CRYPTO_GETFIELD_OK is success,
3556 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3557 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3558 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003559 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003560 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3561 int i;
3562 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003563
3564 if (persist_data == NULL) {
3565 load_persistent_data();
3566 if (persist_data == NULL) {
3567 SLOGE("Getfield error, cannot load persistent data");
3568 goto out;
3569 }
3570 }
3571
Rubin Xu85c01f92014-10-13 12:49:54 +01003572 // Read value from persistent entries. If the original value is split into multiple entries,
3573 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003574 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003575 // We found it, copy it to the caller's buffer and keep going until all entries are read.
3576 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
3577 // value too small
3578 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3579 goto out;
3580 }
3581 rc = CRYPTO_GETFIELD_OK;
3582
3583 for (i = 1; /* break explicitly */; i++) {
3584 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
3585 (int) sizeof(temp_field)) {
3586 // If the fieldname is very long, we stop as soon as it begins to overflow the
3587 // maximum field length. At this point we have in fact fully read out the original
3588 // value because cryptfs_setfield would not allow fields with longer names to be
3589 // written in the first place.
3590 break;
3591 }
3592 if (!persist_get_key(temp_field, temp_value)) {
3593 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3594 // value too small.
3595 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3596 goto out;
3597 }
3598 } else {
3599 // Exhaust all entries.
3600 break;
3601 }
3602 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003603 } else {
3604 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003605 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003606 }
3607
3608out:
3609 return rc;
3610}
3611
3612/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003613int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003614{
Ken Sumrall160b4d62013-04-22 12:15:39 -07003615 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003616 /* 0 is success, negative values are error */
3617 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003618 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003619 unsigned int field_id;
3620 char temp_field[PROPERTY_KEY_MAX];
3621 unsigned int num_entries;
3622 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003623
3624 if (persist_data == NULL) {
3625 load_persistent_data();
3626 if (persist_data == NULL) {
3627 SLOGE("Setfield error, cannot load persistent data");
3628 goto out;
3629 }
3630 }
3631
3632 property_get("ro.crypto.state", encrypted_state, "");
3633 if (!strcmp(encrypted_state, "encrypted") ) {
3634 encrypted = 1;
3635 }
3636
Rubin Xu85c01f92014-10-13 12:49:54 +01003637 // Compute the number of entries required to store value, each entry can store up to
3638 // (PROPERTY_VALUE_MAX - 1) chars
3639 if (strlen(value) == 0) {
3640 // Empty value also needs one entry to store.
3641 num_entries = 1;
3642 } else {
3643 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3644 }
3645
3646 max_keylen = strlen(fieldname);
3647 if (num_entries > 1) {
3648 // Need an extra "_%d" suffix.
3649 max_keylen += 1 + log10(num_entries);
3650 }
3651 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3652 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003653 goto out;
3654 }
3655
Rubin Xu85c01f92014-10-13 12:49:54 +01003656 // Make sure we have enough space to write the new value
3657 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3658 persist_get_max_entries(encrypted)) {
3659 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3660 goto out;
3661 }
3662
3663 // Now that we know persist_data has enough space for value, let's delete the old field first
3664 // to make up space.
3665 persist_del_keys(fieldname, 0);
3666
3667 if (persist_set_key(fieldname, value, encrypted)) {
3668 // fail to set key, should not happen as we have already checked the available space
3669 SLOGE("persist_set_key() error during setfield()");
3670 goto out;
3671 }
3672
3673 for (field_id = 1; field_id < num_entries; field_id++) {
3674 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
3675
3676 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3677 // fail to set key, should not happen as we have already checked the available space.
3678 SLOGE("persist_set_key() error during setfield()");
3679 goto out;
3680 }
3681 }
3682
Ken Sumrall160b4d62013-04-22 12:15:39 -07003683 /* If we are running encrypted, save the persistent data now */
3684 if (encrypted) {
3685 if (save_persistent_data()) {
3686 SLOGE("Setfield error, cannot save persistent data");
3687 goto out;
3688 }
3689 }
3690
Rubin Xu85c01f92014-10-13 12:49:54 +01003691 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003692
3693out:
3694 return rc;
3695}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003696
3697/* Checks userdata. Attempt to mount the volume if default-
3698 * encrypted.
3699 * On success trigger next init phase and return 0.
3700 * Currently do not handle failure - see TODO below.
3701 */
3702int cryptfs_mount_default_encrypted(void)
3703{
3704 char decrypt_state[PROPERTY_VALUE_MAX];
3705 property_get("vold.decrypt", decrypt_state, "0");
3706 if (!strcmp(decrypt_state, "0")) {
3707 SLOGE("Not encrypted - should not call here");
3708 } else {
3709 int crypt_type = cryptfs_get_password_type();
3710 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3711 SLOGE("Bad crypt type - error");
3712 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3713 SLOGD("Password is not default - "
3714 "starting min framework to prompt");
3715 property_set("vold.decrypt", "trigger_restart_min_framework");
3716 return 0;
3717 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3718 SLOGD("Password is default - restarting filesystem");
3719 cryptfs_restart_internal(0);
3720 return 0;
3721 } else {
3722 SLOGE("Encrypted, default crypt type but can't decrypt");
3723 }
3724 }
3725
Paul Lawrence6bfed202014-07-28 12:47:22 -07003726 /** Corrupt. Allow us to boot into framework, which will detect bad
3727 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003728 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003729 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003730 return 0;
3731}
3732
3733/* Returns type of the password, default, pattern, pin or password.
3734 */
3735int cryptfs_get_password_type(void)
3736{
Paul Lawrence05335c32015-03-05 09:46:23 -08003737 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3738 return e4crypt_get_password_type(DATA_MNT_POINT);
3739 }
3740
Paul Lawrencef4faa572014-01-29 13:31:03 -08003741 struct crypt_mnt_ftr crypt_ftr;
3742
3743 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3744 SLOGE("Error getting crypt footer and key\n");
3745 return -1;
3746 }
3747
Paul Lawrence6bfed202014-07-28 12:47:22 -07003748 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3749 return -1;
3750 }
3751
Paul Lawrencef4faa572014-01-29 13:31:03 -08003752 return crypt_ftr.crypt_type;
3753}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003754
Paul Lawrence05335c32015-03-05 09:46:23 -08003755const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003756{
Paul Lawrence05335c32015-03-05 09:46:23 -08003757 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3758 return e4crypt_get_password(DATA_MNT_POINT);
3759 }
3760
Paul Lawrence399317e2014-03-10 13:20:50 -07003761 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003762 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003763 if (now.tv_sec < password_expiry_time) {
3764 return password;
3765 } else {
3766 cryptfs_clear_password();
3767 return 0;
3768 }
3769}
3770
3771void cryptfs_clear_password()
3772{
3773 if (password) {
3774 size_t len = strlen(password);
3775 memset(password, 0, len);
3776 free(password);
3777 password = 0;
3778 password_expiry_time = 0;
3779 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003780}