blob: 563acbc2d06e857a3b5c0300a11ef93c216f4e4a [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>
39#include <errno.h>
Ken Sumrall3ed82362011-01-28 23:31:16 -080040#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070041#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070042#include <fs_mgr.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080043#include "cryptfs.h"
44#define LOG_TAG "Cryptfs"
45#include "cutils/log.h"
46#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070047#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080048#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070049#include <logwrap/logwrap.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070050#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070051#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070052#include "crypto_scrypt.h"
Paul Lawrenceae59fe62014-01-21 08:23:27 -080053#include "ext4_utils.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000054#include "f2fs_sparseblock.h"
Paul Lawrence87999172014-02-20 12:21:31 -080055#include "CheckBattery.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080056
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070057#include <hardware/keymaster.h>
58
Mark Salyzyn3e971272014-01-21 13:27:04 -080059#define UNUSED __attribute__((unused))
60
Mark Salyzyn5eecc442014-02-12 14:16:14 -080061#define UNUSED __attribute__((unused))
62
Ken Sumrall8f869aa2010-12-03 03:47:09 -080063#define DM_CRYPT_BUF_SIZE 4096
64
Jason parks70a4b3f2011-01-28 10:10:47 -060065#define HASH_COUNT 2000
66#define KEY_LEN_BYTES 16
67#define IV_LEN_BYTES 16
68
Ken Sumrall29d8da82011-05-18 17:20:07 -070069#define KEY_IN_FOOTER "footer"
70
Paul Lawrencef4faa572014-01-29 13:31:03 -080071// "default_password" encoded into hex (d=0x64 etc)
72#define DEFAULT_PASSWORD "64656661756c745f70617373776f7264"
73
Ken Sumrall29d8da82011-05-18 17:20:07 -070074#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070075#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070076
Ken Sumralle919efe2012-09-29 17:07:41 -070077#define TABLE_LOAD_RETRIES 10
78
Shawn Willden47ba10d2014-09-03 17:07:06 -060079#define RSA_KEY_SIZE 2048
80#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
81#define RSA_EXPONENT 0x10001
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070082
Ken Sumrall8f869aa2010-12-03 03:47:09 -080083char *me = "cryptfs";
84
Jason parks70a4b3f2011-01-28 10:10:47 -060085static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070086static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060087static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -070088static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -080089
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070090static int keymaster_init(keymaster_device_t **keymaster_dev)
91{
92 int rc;
93
94 const hw_module_t* mod;
95 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
96 if (rc) {
97 ALOGE("could not find any keystore module");
98 goto out;
99 }
100
101 rc = keymaster_open(mod, keymaster_dev);
102 if (rc) {
103 ALOGE("could not open keymaster device in %s (%s)",
104 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
105 goto out;
106 }
107
108 return 0;
109
110out:
111 *keymaster_dev = NULL;
112 return rc;
113}
114
115/* Should we use keymaster? */
116static int keymaster_check_compatibility()
117{
118 keymaster_device_t *keymaster_dev = 0;
119 int rc = 0;
120
121 if (keymaster_init(&keymaster_dev)) {
122 SLOGE("Failed to init keymaster");
123 rc = -1;
124 goto out;
125 }
126
Paul Lawrence8c008392014-05-06 14:02:48 -0700127 SLOGI("keymaster version is %d", keymaster_dev->common.module->module_api_version);
128
129 if (keymaster_dev->common.module->module_api_version
130 < KEYMASTER_MODULE_API_VERSION_0_3) {
131 rc = 0;
132 goto out;
133 }
134
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700135 if (keymaster_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE) {
136 rc = 1;
137 }
138
139out:
140 keymaster_close(keymaster_dev);
141 return rc;
142}
143
144/* Create a new keymaster key and store it in this footer */
145static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
146{
147 uint8_t* key = 0;
148 keymaster_device_t *keymaster_dev = 0;
149
150 if (keymaster_init(&keymaster_dev)) {
151 SLOGE("Failed to init keymaster");
152 return -1;
153 }
154
155 int rc = 0;
156
157 keymaster_rsa_keygen_params_t params;
158 memset(&params, '\0', sizeof(params));
Shawn Willden47ba10d2014-09-03 17:07:06 -0600159 params.public_exponent = RSA_EXPONENT;
160 params.modulus_size = RSA_KEY_SIZE;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700161
162 size_t key_size;
163 if (keymaster_dev->generate_keypair(keymaster_dev, TYPE_RSA, &params,
164 &key, &key_size)) {
165 SLOGE("Failed to generate keypair");
166 rc = -1;
167 goto out;
168 }
169
170 if (key_size > KEYMASTER_BLOB_SIZE) {
171 SLOGE("Keymaster key too large for crypto footer");
172 rc = -1;
173 goto out;
174 }
175
176 memcpy(ftr->keymaster_blob, key, key_size);
177 ftr->keymaster_blob_size = key_size;
178
179out:
180 keymaster_close(keymaster_dev);
181 free(key);
182 return rc;
183}
184
Shawn Willden47ba10d2014-09-03 17:07:06 -0600185/* This signs the given object using the keymaster key. It incorrectly
186 * signs a too-short value which shouldn't work but somehow does on some
187 * keymaster implementations.
188 */
189static int keymaster_sign_object_improperly(struct crypt_mnt_ftr *ftr,
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700190 const unsigned char *object,
191 const size_t object_size,
192 unsigned char **signature,
193 size_t *signature_size)
194{
195 int rc = 0;
196 keymaster_device_t *keymaster_dev = 0;
197 if (keymaster_init(&keymaster_dev)) {
198 SLOGE("Failed to init keymaster");
199 return -1;
200 }
201
202 /* We currently set the digest type to DIGEST_NONE because it's the
203 * only supported value for keymaster. A similar issue exists with
204 * PADDING_NONE. Long term both of these should likely change.
205 */
206 keymaster_rsa_sign_params_t params;
207 params.digest_type = DIGEST_NONE;
208 params.padding_type = PADDING_NONE;
209
Shawn Willden47ba10d2014-09-03 17:07:06 -0600210 SLOGE("Signing unpadded object");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700211 rc = keymaster_dev->sign_data(keymaster_dev,
212 &params,
213 ftr->keymaster_blob,
214 ftr->keymaster_blob_size,
215 object,
216 object_size,
217 signature,
218 signature_size);
219
220 keymaster_close(keymaster_dev);
221 return rc;
222}
223
Shawn Willden47ba10d2014-09-03 17:07:06 -0600224/* This signs the given object using the keymaster key, correctly. */
225static int keymaster_sign_object_properly(struct crypt_mnt_ftr *ftr,
226 const unsigned char *object,
227 const size_t object_size,
228 unsigned char **signature,
229 size_t *signature_size)
230{
231 int rc = 0;
232 keymaster_device_t *keymaster_dev = 0;
233 if (keymaster_init(&keymaster_dev)) {
234 SLOGE("Failed to init keymaster");
235 return -1;
236 }
237
238 /* We currently set the digest type to DIGEST_NONE because it's the
239 * only supported value for keymaster. A similar issue exists with
240 * PADDING_NONE. Long term both of these should likely change.
241 */
242 keymaster_rsa_sign_params_t params;
243 params.digest_type = DIGEST_NONE;
244 params.padding_type = PADDING_NONE;
245
246 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
247 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
248 memcpy(to_sign, object, min(RSA_KEY_SIZE_BYTES, object_size));
249
250 SLOGI("Signing padded object");
251 rc = keymaster_dev->sign_data(keymaster_dev,
252 &params,
253 ftr->keymaster_blob,
254 ftr->keymaster_blob_size,
255 to_sign,
256 RSA_KEY_SIZE_BYTES,
257 signature,
258 signature_size);
259
260 keymaster_close(keymaster_dev);
261 return rc;
262}
263
Paul Lawrence399317e2014-03-10 13:20:50 -0700264/* Store password when userdata is successfully decrypted and mounted.
265 * Cleared by cryptfs_clear_password
266 *
267 * To avoid a double prompt at boot, we need to store the CryptKeeper
268 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
269 * Since the entire framework is torn down and rebuilt after encryption,
270 * we have to use a daemon or similar to store the password. Since vold
271 * is secured against IPC except from system processes, it seems a reasonable
272 * place to store this.
273 *
274 * password should be cleared once it has been used.
275 *
276 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800277 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700278static char* password = 0;
279static int password_expiry_time = 0;
280static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800281
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800282extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800283
Paul Lawrence87999172014-02-20 12:21:31 -0800284enum RebootType {reboot, recovery, shutdown};
285static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700286{
Paul Lawrence87999172014-02-20 12:21:31 -0800287 switch(rt) {
288 case reboot:
289 property_set(ANDROID_RB_PROPERTY, "reboot");
290 break;
291
292 case recovery:
293 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
294 break;
295
296 case shutdown:
297 property_set(ANDROID_RB_PROPERTY, "shutdown");
298 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700299 }
Paul Lawrence87999172014-02-20 12:21:31 -0800300
Ken Sumralladfba362013-06-04 16:37:52 -0700301 sleep(20);
302
303 /* Shouldn't get here, reboot should happen before sleep times out */
304 return;
305}
306
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800307static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
308{
309 memset(io, 0, dataSize);
310 io->data_size = dataSize;
311 io->data_start = sizeof(struct dm_ioctl);
312 io->version[0] = 4;
313 io->version[1] = 0;
314 io->version[2] = 0;
315 io->flags = flags;
316 if (name) {
317 strncpy(io->name, name, sizeof(io->name));
318 }
319}
320
Kenny Rootc4c70f12013-06-14 12:11:38 -0700321/**
322 * Gets the default device scrypt parameters for key derivation time tuning.
323 * The parameters should lead to about one second derivation time for the
324 * given device.
325 */
326static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
327 const int default_params[] = SCRYPT_DEFAULTS;
328 int params[] = SCRYPT_DEFAULTS;
329 char paramstr[PROPERTY_VALUE_MAX];
330 char *token;
331 char *saveptr;
332 int i;
333
334 property_get(SCRYPT_PROP, paramstr, "");
335 if (paramstr[0] != '\0') {
336 /*
337 * The token we're looking for should be three integers separated by
338 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
339 */
Kenny Root2947e342013-08-14 15:54:49 -0700340 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
341 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700342 i++, token = strtok_r(NULL, ":", &saveptr)) {
343 char *endptr;
344 params[i] = strtol(token, &endptr, 10);
345
346 /*
347 * Check that there was a valid number and it's 8-bit. If not,
348 * break out and the end check will take the default values.
349 */
350 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
351 break;
352 }
353 }
354
355 /*
356 * If there were not enough tokens or a token was malformed (not an
357 * integer), it will end up here and the default parameters can be
358 * taken.
359 */
360 if ((i != 3) || (token != NULL)) {
361 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
362 memcpy(params, default_params, sizeof(params));
363 }
364 }
365
366 ftr->N_factor = params[0];
367 ftr->r_factor = params[1];
368 ftr->p_factor = params[2];
369}
370
Ken Sumrall3ed82362011-01-28 23:31:16 -0800371static unsigned int get_fs_size(char *dev)
372{
373 int fd, block_size;
374 struct ext4_super_block sb;
375 off64_t len;
376
377 if ((fd = open(dev, O_RDONLY)) < 0) {
378 SLOGE("Cannot open device to get filesystem size ");
379 return 0;
380 }
381
382 if (lseek64(fd, 1024, SEEK_SET) < 0) {
383 SLOGE("Cannot seek to superblock");
384 return 0;
385 }
386
387 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
388 SLOGE("Cannot read superblock");
389 return 0;
390 }
391
392 close(fd);
393
Daniel Rosenberge82df162014-08-15 22:19:23 +0000394 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
395 SLOGE("Not a valid ext4 superblock");
396 return 0;
397 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800398 block_size = 1024 << sb.s_log_block_size;
399 /* compute length in bytes */
400 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
401
402 /* return length in sectors */
403 return (unsigned int) (len / 512);
404}
405
Ken Sumrall160b4d62013-04-22 12:15:39 -0700406static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
407{
408 static int cached_data = 0;
409 static off64_t cached_off = 0;
410 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
411 int fd;
412 char key_loc[PROPERTY_VALUE_MAX];
413 char real_blkdev[PROPERTY_VALUE_MAX];
414 unsigned int nr_sec;
415 int rc = -1;
416
417 if (!cached_data) {
418 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
419
420 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
421 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
422 SLOGE("Cannot open real block device %s\n", real_blkdev);
423 return -1;
424 }
425
426 if ((nr_sec = get_blkdev_size(fd))) {
427 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
428 * encryption info footer and key, and plenty of bytes to spare for future
429 * growth.
430 */
431 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
432 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
433 cached_data = 1;
434 } else {
435 SLOGE("Cannot get size of block device %s\n", real_blkdev);
436 }
437 close(fd);
438 } else {
439 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
440 cached_off = 0;
441 cached_data = 1;
442 }
443 }
444
445 if (cached_data) {
446 if (metadata_fname) {
447 *metadata_fname = cached_metadata_fname;
448 }
449 if (off) {
450 *off = cached_off;
451 }
452 rc = 0;
453 }
454
455 return rc;
456}
457
Ken Sumralle8744072011-01-18 22:01:55 -0800458/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800459 * update the failed mount count but not change the key.
460 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700461static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800462{
463 int fd;
464 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700465 /* starting_off is set to the SEEK_SET offset
466 * where the crypto structure starts
467 */
468 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800469 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700470 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700471 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800472
Ken Sumrall160b4d62013-04-22 12:15:39 -0700473 if (get_crypt_ftr_info(&fname, &starting_off)) {
474 SLOGE("Unable to get crypt_ftr_info\n");
475 return -1;
476 }
477 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700478 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700479 return -1;
480 }
Ken Sumralle550f782013-08-20 13:48:23 -0700481 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
482 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700483 return -1;
484 }
485
486 /* Seek to the start of the crypt footer */
487 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
488 SLOGE("Cannot seek to real block device footer\n");
489 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800490 }
491
492 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
493 SLOGE("Cannot write real block device footer\n");
494 goto errout;
495 }
496
Ken Sumrall3be890f2011-09-14 16:53:46 -0700497 fstat(fd, &statbuf);
498 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700499 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700500 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800501 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800502 goto errout;
503 }
504 }
505
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800506 /* Success! */
507 rc = 0;
508
509errout:
510 close(fd);
511 return rc;
512
513}
514
Ken Sumrall160b4d62013-04-22 12:15:39 -0700515static inline int unix_read(int fd, void* buff, int len)
516{
517 return TEMP_FAILURE_RETRY(read(fd, buff, len));
518}
519
520static inline int unix_write(int fd, const void* buff, int len)
521{
522 return TEMP_FAILURE_RETRY(write(fd, buff, len));
523}
524
525static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
526{
527 memset(pdata, 0, len);
528 pdata->persist_magic = PERSIST_DATA_MAGIC;
529 pdata->persist_valid_entries = 0;
530}
531
532/* A routine to update the passed in crypt_ftr to the lastest version.
533 * fd is open read/write on the device that holds the crypto footer and persistent
534 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
535 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
536 */
537static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
538{
Kenny Root7434b312013-06-14 11:29:53 -0700539 int orig_major = crypt_ftr->major_version;
540 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700541
Kenny Root7434b312013-06-14 11:29:53 -0700542 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
543 struct crypt_persist_data *pdata;
544 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700545
Kenny Rootc4c70f12013-06-14 12:11:38 -0700546 SLOGW("upgrading crypto footer to 1.1");
547
Kenny Root7434b312013-06-14 11:29:53 -0700548 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
549 if (pdata == NULL) {
550 SLOGE("Cannot allocate persisent data\n");
551 return;
552 }
553 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
554
555 /* Need to initialize the persistent data area */
556 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
557 SLOGE("Cannot seek to persisent data offset\n");
558 return;
559 }
560 /* Write all zeros to the first copy, making it invalid */
561 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
562
563 /* Write a valid but empty structure to the second copy */
564 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
565 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
566
567 /* Update the footer */
568 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
569 crypt_ftr->persist_data_offset[0] = pdata_offset;
570 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
571 crypt_ftr->minor_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700572 }
573
Paul Lawrencef4faa572014-01-29 13:31:03 -0800574 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700575 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800576 /* But keep the old kdf_type.
577 * It will get updated later to KDF_SCRYPT after the password has been verified.
578 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700579 crypt_ftr->kdf_type = KDF_PBKDF2;
580 get_device_scrypt_params(crypt_ftr);
581 crypt_ftr->minor_version = 2;
582 }
583
Paul Lawrencef4faa572014-01-29 13:31:03 -0800584 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
585 SLOGW("upgrading crypto footer to 1.3");
586 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
587 crypt_ftr->minor_version = 3;
588 }
589
Kenny Root7434b312013-06-14 11:29:53 -0700590 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
591 if (lseek64(fd, offset, SEEK_SET) == -1) {
592 SLOGE("Cannot seek to crypt footer\n");
593 return;
594 }
595 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700596 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700597}
598
599
600static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800601{
602 int fd;
603 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700604 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800605 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700606 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700607 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800608
Ken Sumrall160b4d62013-04-22 12:15:39 -0700609 if (get_crypt_ftr_info(&fname, &starting_off)) {
610 SLOGE("Unable to get crypt_ftr_info\n");
611 return -1;
612 }
613 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700614 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700615 return -1;
616 }
617 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700618 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700619 return -1;
620 }
621
622 /* Make sure it's 16 Kbytes in length */
623 fstat(fd, &statbuf);
624 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
625 SLOGE("footer file %s is not the expected size!\n", fname);
626 goto errout;
627 }
628
629 /* Seek to the start of the crypt footer */
630 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
631 SLOGE("Cannot seek to real block device footer\n");
632 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800633 }
634
635 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
636 SLOGE("Cannot read real block device footer\n");
637 goto errout;
638 }
639
640 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700641 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800642 goto errout;
643 }
644
Kenny Rootc96a5f82013-06-14 12:08:28 -0700645 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
646 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
647 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800648 goto errout;
649 }
650
Kenny Rootc96a5f82013-06-14 12:08:28 -0700651 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
652 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
653 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800654 }
655
Ken Sumrall160b4d62013-04-22 12:15:39 -0700656 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
657 * copy on disk before returning.
658 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700659 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700660 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800661 }
662
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800663 /* Success! */
664 rc = 0;
665
666errout:
667 close(fd);
668 return rc;
669}
670
Ken Sumrall160b4d62013-04-22 12:15:39 -0700671static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
672{
673 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
674 crypt_ftr->persist_data_offset[1]) {
675 SLOGE("Crypt_ftr persist data regions overlap");
676 return -1;
677 }
678
679 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
680 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
681 return -1;
682 }
683
684 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
685 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
686 CRYPT_FOOTER_OFFSET) {
687 SLOGE("Persistent data extends past crypto footer");
688 return -1;
689 }
690
691 return 0;
692}
693
694static int load_persistent_data(void)
695{
696 struct crypt_mnt_ftr crypt_ftr;
697 struct crypt_persist_data *pdata = NULL;
698 char encrypted_state[PROPERTY_VALUE_MAX];
699 char *fname;
700 int found = 0;
701 int fd;
702 int ret;
703 int i;
704
705 if (persist_data) {
706 /* Nothing to do, we've already loaded or initialized it */
707 return 0;
708 }
709
710
711 /* If not encrypted, just allocate an empty table and initialize it */
712 property_get("ro.crypto.state", encrypted_state, "");
713 if (strcmp(encrypted_state, "encrypted") ) {
714 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
715 if (pdata) {
716 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
717 persist_data = pdata;
718 return 0;
719 }
720 return -1;
721 }
722
723 if(get_crypt_ftr_and_key(&crypt_ftr)) {
724 return -1;
725 }
726
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700727 if ((crypt_ftr.major_version < 1)
728 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700729 SLOGE("Crypt_ftr version doesn't support persistent data");
730 return -1;
731 }
732
733 if (get_crypt_ftr_info(&fname, NULL)) {
734 return -1;
735 }
736
737 ret = validate_persistent_data_storage(&crypt_ftr);
738 if (ret) {
739 return -1;
740 }
741
742 fd = open(fname, O_RDONLY);
743 if (fd < 0) {
744 SLOGE("Cannot open %s metadata file", fname);
745 return -1;
746 }
747
748 if (persist_data == NULL) {
749 pdata = malloc(crypt_ftr.persist_data_size);
750 if (pdata == NULL) {
751 SLOGE("Cannot allocate memory for persistent data");
752 goto err;
753 }
754 }
755
756 for (i = 0; i < 2; i++) {
757 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
758 SLOGE("Cannot seek to read persistent data on %s", fname);
759 goto err2;
760 }
761 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
762 SLOGE("Error reading persistent data on iteration %d", i);
763 goto err2;
764 }
765 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
766 found = 1;
767 break;
768 }
769 }
770
771 if (!found) {
772 SLOGI("Could not find valid persistent data, creating");
773 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
774 }
775
776 /* Success */
777 persist_data = pdata;
778 close(fd);
779 return 0;
780
781err2:
782 free(pdata);
783
784err:
785 close(fd);
786 return -1;
787}
788
789static int save_persistent_data(void)
790{
791 struct crypt_mnt_ftr crypt_ftr;
792 struct crypt_persist_data *pdata;
793 char *fname;
794 off64_t write_offset;
795 off64_t erase_offset;
796 int found = 0;
797 int fd;
798 int ret;
799
800 if (persist_data == NULL) {
801 SLOGE("No persistent data to save");
802 return -1;
803 }
804
805 if(get_crypt_ftr_and_key(&crypt_ftr)) {
806 return -1;
807 }
808
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700809 if ((crypt_ftr.major_version < 1)
810 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700811 SLOGE("Crypt_ftr version doesn't support persistent data");
812 return -1;
813 }
814
815 ret = validate_persistent_data_storage(&crypt_ftr);
816 if (ret) {
817 return -1;
818 }
819
820 if (get_crypt_ftr_info(&fname, NULL)) {
821 return -1;
822 }
823
824 fd = open(fname, O_RDWR);
825 if (fd < 0) {
826 SLOGE("Cannot open %s metadata file", fname);
827 return -1;
828 }
829
830 pdata = malloc(crypt_ftr.persist_data_size);
831 if (pdata == NULL) {
832 SLOGE("Cannot allocate persistant data");
833 goto err;
834 }
835
836 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
837 SLOGE("Cannot seek to read persistent data on %s", fname);
838 goto err2;
839 }
840
841 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
842 SLOGE("Error reading persistent data before save");
843 goto err2;
844 }
845
846 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
847 /* The first copy is the curent valid copy, so write to
848 * the second copy and erase this one */
849 write_offset = crypt_ftr.persist_data_offset[1];
850 erase_offset = crypt_ftr.persist_data_offset[0];
851 } else {
852 /* The second copy must be the valid copy, so write to
853 * the first copy, and erase the second */
854 write_offset = crypt_ftr.persist_data_offset[0];
855 erase_offset = crypt_ftr.persist_data_offset[1];
856 }
857
858 /* Write the new copy first, if successful, then erase the old copy */
859 if (lseek(fd, write_offset, SEEK_SET) < 0) {
860 SLOGE("Cannot seek to write persistent data");
861 goto err2;
862 }
863 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
864 (int) crypt_ftr.persist_data_size) {
865 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
866 SLOGE("Cannot seek to erase previous persistent data");
867 goto err2;
868 }
869 fsync(fd);
870 memset(pdata, 0, crypt_ftr.persist_data_size);
871 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
872 (int) crypt_ftr.persist_data_size) {
873 SLOGE("Cannot write to erase previous persistent data");
874 goto err2;
875 }
876 fsync(fd);
877 } else {
878 SLOGE("Cannot write to save persistent data");
879 goto err2;
880 }
881
882 /* Success */
883 free(pdata);
884 close(fd);
885 return 0;
886
887err2:
888 free(pdata);
889err:
890 close(fd);
891 return -1;
892}
893
Paul Lawrencef4faa572014-01-29 13:31:03 -0800894static int hexdigit (char c)
895{
896 if (c >= '0' && c <= '9') return c - '0';
897 c = tolower(c);
898 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
899 return -1;
900}
901
902static unsigned char* convert_hex_ascii_to_key(const char* master_key_ascii,
903 unsigned int* out_keysize)
904{
905 unsigned int i;
906 *out_keysize = 0;
907
908 size_t size = strlen (master_key_ascii);
909 if (size % 2) {
910 SLOGE("Trying to convert ascii string of odd length");
911 return NULL;
912 }
913
914 unsigned char* master_key = (unsigned char*) malloc(size / 2);
915 if (master_key == 0) {
916 SLOGE("Cannot allocate");
917 return NULL;
918 }
919
920 for (i = 0; i < size; i += 2) {
921 int high_nibble = hexdigit (master_key_ascii[i]);
922 int low_nibble = hexdigit (master_key_ascii[i + 1]);
923
924 if(high_nibble < 0 || low_nibble < 0) {
925 SLOGE("Invalid hex string");
926 free (master_key);
927 return NULL;
928 }
929
930 master_key[*out_keysize] = high_nibble * 16 + low_nibble;
931 (*out_keysize)++;
932 }
933
934 return master_key;
935}
936
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800937/* Convert a binary key of specified length into an ascii hex string equivalent,
938 * without the leading 0x and with null termination
939 */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800940static void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800941 char *master_key_ascii)
942{
943 unsigned int i, a;
944 unsigned char nibble;
945
946 for (i=0, a=0; i<keysize; i++, a+=2) {
947 /* For each byte, write out two ascii hex digits */
948 nibble = (master_key[i] >> 4) & 0xf;
949 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
950
951 nibble = master_key[i] & 0xf;
952 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
953 }
954
955 /* Add the null termination */
956 master_key_ascii[a] = '\0';
957
958}
959
Ken Sumralldb5e0262013-02-05 17:39:48 -0800960static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
961 char *real_blk_name, const char *name, int fd,
962 char *extra_params)
963{
964 char buffer[DM_CRYPT_BUF_SIZE];
965 struct dm_ioctl *io;
966 struct dm_target_spec *tgt;
967 char *crypt_params;
968 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
969 int i;
970
971 io = (struct dm_ioctl *) buffer;
972
973 /* Load the mapping table for this device */
974 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
975
976 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
977 io->target_count = 1;
978 tgt->status = 0;
979 tgt->sector_start = 0;
980 tgt->length = crypt_ftr->fs_size;
981 strcpy(tgt->target_type, "crypt");
982
983 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
984 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
985 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
986 master_key_ascii, real_blk_name, extra_params);
987 crypt_params += strlen(crypt_params) + 1;
988 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
989 tgt->next = crypt_params - buffer;
990
991 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
992 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
993 break;
994 }
995 usleep(500000);
996 }
997
998 if (i == TABLE_LOAD_RETRIES) {
999 /* We failed to load the table, return an error */
1000 return -1;
1001 } else {
1002 return i + 1;
1003 }
1004}
1005
1006
1007static int get_dm_crypt_version(int fd, const char *name, int *version)
1008{
1009 char buffer[DM_CRYPT_BUF_SIZE];
1010 struct dm_ioctl *io;
1011 struct dm_target_versions *v;
1012 int i;
1013
1014 io = (struct dm_ioctl *) buffer;
1015
1016 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1017
1018 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1019 return -1;
1020 }
1021
1022 /* Iterate over the returned versions, looking for name of "crypt".
1023 * When found, get and return the version.
1024 */
1025 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1026 while (v->next) {
1027 if (! strcmp(v->name, "crypt")) {
1028 /* We found the crypt driver, return the version, and get out */
1029 version[0] = v->version[0];
1030 version[1] = v->version[1];
1031 version[2] = v->version[2];
1032 return 0;
1033 }
1034 v = (struct dm_target_versions *)(((char *)v) + v->next);
1035 }
1036
1037 return -1;
1038}
1039
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001040static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -07001041 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001042{
1043 char buffer[DM_CRYPT_BUF_SIZE];
1044 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
1045 char *crypt_params;
1046 struct dm_ioctl *io;
1047 struct dm_target_spec *tgt;
1048 unsigned int minor;
1049 int fd;
Ken Sumralle919efe2012-09-29 17:07:41 -07001050 int i;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001051 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001052 int version[3];
1053 char *extra_params;
1054 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001055
1056 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1057 SLOGE("Cannot open device-mapper\n");
1058 goto errout;
1059 }
1060
1061 io = (struct dm_ioctl *) buffer;
1062
1063 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1064 if (ioctl(fd, DM_DEV_CREATE, io)) {
1065 SLOGE("Cannot create dm-crypt device\n");
1066 goto errout;
1067 }
1068
1069 /* Get the device status, in particular, the name of it's device file */
1070 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1071 if (ioctl(fd, DM_DEV_STATUS, io)) {
1072 SLOGE("Cannot retrieve dm-crypt device status\n");
1073 goto errout;
1074 }
1075 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1076 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1077
Ken Sumralldb5e0262013-02-05 17:39:48 -08001078 extra_params = "";
1079 if (! get_dm_crypt_version(fd, name, version)) {
1080 /* Support for allow_discards was added in version 1.11.0 */
1081 if ((version[0] >= 2) ||
1082 ((version[0] == 1) && (version[1] >= 11))) {
1083 extra_params = "1 allow_discards";
1084 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1085 }
Ken Sumralle919efe2012-09-29 17:07:41 -07001086 }
1087
Ken Sumralldb5e0262013-02-05 17:39:48 -08001088 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1089 fd, extra_params);
1090 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001091 SLOGE("Cannot load dm-crypt mapping table.\n");
1092 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001093 } else if (load_count > 1) {
1094 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001095 }
1096
1097 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -08001098 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001099
1100 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1101 SLOGE("Cannot resume the dm-crypt device\n");
1102 goto errout;
1103 }
1104
1105 /* We made it here with no errors. Woot! */
1106 retval = 0;
1107
1108errout:
1109 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1110
1111 return retval;
1112}
1113
Ken Sumrall29d8da82011-05-18 17:20:07 -07001114static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001115{
1116 int fd;
1117 char buffer[DM_CRYPT_BUF_SIZE];
1118 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001119 int retval = -1;
1120
1121 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1122 SLOGE("Cannot open device-mapper\n");
1123 goto errout;
1124 }
1125
1126 io = (struct dm_ioctl *) buffer;
1127
1128 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1129 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1130 SLOGE("Cannot remove dm-crypt device\n");
1131 goto errout;
1132 }
1133
1134 /* We made it here with no errors. Woot! */
1135 retval = 0;
1136
1137errout:
1138 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1139
1140 return retval;
1141
1142}
1143
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001144static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001145 unsigned char *ikey, void *params UNUSED)
1146{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001147 SLOGI("Using pbkdf2 for cryptfs KDF");
1148
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001149 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001150 unsigned int keysize;
1151 char* master_key = (char*)convert_hex_ascii_to_key(passwd, &keysize);
1152 if (!master_key) return -1;
1153 PKCS5_PBKDF2_HMAC_SHA1(master_key, keysize, salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001154 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001155
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001156 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001157 free (master_key);
1158 return 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001159}
1160
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001161static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001162 unsigned char *ikey, void *params)
1163{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001164 SLOGI("Using scrypt for cryptfs KDF");
1165
Kenny Rootc4c70f12013-06-14 12:11:38 -07001166 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1167
1168 int N = 1 << ftr->N_factor;
1169 int r = 1 << ftr->r_factor;
1170 int p = 1 << ftr->p_factor;
1171
1172 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001173 unsigned int keysize;
1174 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &keysize);
1175 if (!master_key) return -1;
1176 crypto_scrypt(master_key, keysize, salt, SALT_LEN, N, r, p, ikey,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001177 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001178
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001179 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001180 free (master_key);
1181 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001182}
1183
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001184static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1185 unsigned char *ikey, void *params)
1186{
1187 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1188
1189 int rc;
1190 unsigned int key_size;
1191 size_t signature_size;
1192 unsigned char* signature;
1193 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1194
1195 int N = 1 << ftr->N_factor;
1196 int r = 1 << ftr->r_factor;
1197 int p = 1 << ftr->p_factor;
1198
1199 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &key_size);
1200 if (!master_key) {
1201 SLOGE("Failed to convert passwd from hex");
1202 return -1;
1203 }
1204
1205 rc = crypto_scrypt(master_key, key_size, salt, SALT_LEN,
1206 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1207 memset(master_key, 0, key_size);
1208 free(master_key);
1209
1210 if (rc) {
1211 SLOGE("scrypt failed");
1212 return -1;
1213 }
1214
Shawn Willden47ba10d2014-09-03 17:07:06 -06001215 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER_IMPROPER) {
1216 if (keymaster_sign_object_improperly(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1217 &signature, &signature_size)) {
1218 SLOGE("Signing failed");
1219 return -1;
1220 }
1221 } else {
1222 if (keymaster_sign_object_properly(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1223 &signature, &signature_size)) {
1224 SLOGE("Signing failed");
1225 return -1;
1226 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001227 }
1228
1229 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1230 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1231 free(signature);
1232
1233 if (rc) {
1234 SLOGE("scrypt failed");
1235 return -1;
1236 }
1237
1238 return 0;
1239}
1240
1241static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1242 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001243 unsigned char *encrypted_master_key,
1244 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001245{
1246 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1247 EVP_CIPHER_CTX e_ctx;
1248 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001249 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001250
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001251 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001252 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001253
1254 switch (crypt_ftr->kdf_type) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001255 case KDF_SCRYPT_KEYMASTER_IMPROPER:
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001256 case KDF_SCRYPT_KEYMASTER:
1257 if (keymaster_create_key(crypt_ftr)) {
1258 SLOGE("keymaster_create_key failed");
1259 return -1;
1260 }
1261
1262 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1263 SLOGE("scrypt failed");
1264 return -1;
1265 }
1266 break;
1267
1268 case KDF_SCRYPT:
1269 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1270 SLOGE("scrypt failed");
1271 return -1;
1272 }
1273 break;
1274
1275 default:
1276 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001277 return -1;
1278 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001279
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001280 /* Initialize the decryption engine */
1281 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1282 SLOGE("EVP_EncryptInit failed\n");
1283 return -1;
1284 }
1285 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001286
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001287 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001288 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
1289 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001290 SLOGE("EVP_EncryptUpdate failed\n");
1291 return -1;
1292 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001293 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001294 SLOGE("EVP_EncryptFinal failed\n");
1295 return -1;
1296 }
1297
1298 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1299 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1300 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001301 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001302
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001303 /* Store the scrypt of the intermediate key, so we can validate if it's a
1304 password error or mount error when things go wrong.
1305 Note there's no need to check for errors, since if this is incorrect, we
1306 simply won't wipe userdata, which is the correct default behavior
1307 */
1308 int N = 1 << crypt_ftr->N_factor;
1309 int r = 1 << crypt_ftr->r_factor;
1310 int p = 1 << crypt_ftr->p_factor;
1311
1312 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1313 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1314 crypt_ftr->scrypted_intermediate_key,
1315 sizeof(crypt_ftr->scrypted_intermediate_key));
1316
1317 if (rc) {
1318 SLOGE("encrypt_master_key: crypto_scrypt failed");
1319 }
1320
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001321 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001322}
1323
JP Abgrall7bdfa522013-11-15 13:42:56 -08001324static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001325 unsigned char *encrypted_master_key,
1326 unsigned char *decrypted_master_key,
1327 kdf_func kdf, void *kdf_params,
1328 unsigned char** intermediate_key,
1329 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001330{
1331 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 -08001332 EVP_CIPHER_CTX d_ctx;
1333 int decrypted_len, final_len;
1334
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001335 /* Turn the password into an intermediate key and IV that can decrypt the
1336 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001337 if (kdf(passwd, salt, ikey, kdf_params)) {
1338 SLOGE("kdf failed");
1339 return -1;
1340 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001341
1342 /* Initialize the decryption engine */
1343 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1344 return -1;
1345 }
1346 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1347 /* Decrypt the master key */
1348 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1349 encrypted_master_key, KEY_LEN_BYTES)) {
1350 return -1;
1351 }
1352 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1353 return -1;
1354 }
1355
1356 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1357 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001358 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001359
1360 /* Copy intermediate key if needed by params */
1361 if (intermediate_key && intermediate_key_size) {
1362 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1363 if (intermediate_key) {
1364 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1365 *intermediate_key_size = KEY_LEN_BYTES;
1366 }
1367 }
1368
1369 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001370}
1371
Kenny Rootc4c70f12013-06-14 12:11:38 -07001372static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001373{
Shawn Willden47ba10d2014-09-03 17:07:06 -06001374 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER_IMPROPER || ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001375 *kdf = scrypt_keymaster;
1376 *kdf_params = ftr;
1377 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001378 *kdf = scrypt;
1379 *kdf_params = ftr;
1380 } else {
1381 *kdf = pbkdf2;
1382 *kdf_params = NULL;
1383 }
1384}
1385
JP Abgrall7bdfa522013-11-15 13:42:56 -08001386static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001387 struct crypt_mnt_ftr *crypt_ftr,
1388 unsigned char** intermediate_key,
1389 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001390{
1391 kdf_func kdf;
1392 void *kdf_params;
1393 int ret;
1394
1395 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001396 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1397 decrypted_master_key, kdf, kdf_params,
1398 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001399 if (ret != 0) {
1400 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001401 }
1402
1403 return ret;
1404}
1405
1406static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1407 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001408 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001409 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001410 EVP_CIPHER_CTX e_ctx;
1411 int encrypted_len, final_len;
1412
1413 /* Get some random bits for a key */
1414 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001415 read(fd, key_buf, sizeof(key_buf));
1416 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001417 close(fd);
1418
1419 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001420 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001421}
1422
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001423static int wait_and_unmount(char *mountpoint)
1424{
1425 int i, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001426#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001427
1428 /* Now umount the tmpfs filesystem */
1429 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
1430 if (umount(mountpoint)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001431 if (errno == EINVAL) {
1432 /* EINVAL is returned if the directory is not a mountpoint,
1433 * i.e. there is no filesystem mounted there. So just get out.
1434 */
1435 break;
1436 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001437 sleep(1);
1438 i++;
1439 } else {
1440 break;
1441 }
1442 }
1443
1444 if (i < WAIT_UNMOUNT_COUNT) {
1445 SLOGD("unmounting %s succeeded\n", mountpoint);
1446 rc = 0;
1447 } else {
1448 SLOGE("unmounting %s failed\n", mountpoint);
1449 rc = -1;
1450 }
1451
1452 return rc;
1453}
1454
Ken Sumrallc5872692013-05-14 15:26:31 -07001455#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001456static int prep_data_fs(void)
1457{
1458 int i;
1459
1460 /* Do the prep of the /data filesystem */
1461 property_set("vold.post_fs_data_done", "0");
1462 property_set("vold.decrypt", "trigger_post_fs_data");
1463 SLOGD("Just triggered post_fs_data\n");
1464
Ken Sumrallc5872692013-05-14 15:26:31 -07001465 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001466 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001467 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001468
1469 property_get("vold.post_fs_data_done", p, "0");
1470 if (*p == '1') {
1471 break;
1472 } else {
1473 usleep(250000);
1474 }
1475 }
1476 if (i == DATA_PREP_TIMEOUT) {
1477 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001478 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001479 return -1;
1480 } else {
1481 SLOGD("post_fs_data done\n");
1482 return 0;
1483 }
1484}
1485
Paul Lawrence74f29f12014-08-28 15:54:10 -07001486static void cryptfs_set_corrupt()
1487{
1488 // Mark the footer as bad
1489 struct crypt_mnt_ftr crypt_ftr;
1490 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1491 SLOGE("Failed to get crypto footer - panic");
1492 return;
1493 }
1494
1495 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1496 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1497 SLOGE("Failed to set crypto footer - panic");
1498 return;
1499 }
1500}
1501
1502static void cryptfs_trigger_restart_min_framework()
1503{
1504 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1505 SLOGE("Failed to mount tmpfs on data - panic");
1506 return;
1507 }
1508
1509 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1510 SLOGE("Failed to trigger post fs data - panic");
1511 return;
1512 }
1513
1514 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1515 SLOGE("Failed to trigger restart min framework - panic");
1516 return;
1517 }
1518}
1519
Paul Lawrencef4faa572014-01-29 13:31:03 -08001520static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001521{
1522 char fs_type[32];
1523 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001524 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001525 char fs_options[256];
1526 unsigned long mnt_flags;
1527 struct stat statbuf;
1528 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001529 static int restart_successful = 0;
1530
1531 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001532 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001533 SLOGE("Encrypted filesystem not validated, aborting");
1534 return -1;
1535 }
1536
1537 if (restart_successful) {
1538 SLOGE("System already restarted with encrypted disk, aborting");
1539 return -1;
1540 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001541
Paul Lawrencef4faa572014-01-29 13:31:03 -08001542 if (restart_main) {
1543 /* Here is where we shut down the framework. The init scripts
1544 * start all services in one of three classes: core, main or late_start.
1545 * On boot, we start core and main. Now, we stop main, but not core,
1546 * as core includes vold and a few other really important things that
1547 * we need to keep running. Once main has stopped, we should be able
1548 * to umount the tmpfs /data, then mount the encrypted /data.
1549 * We then restart the class main, and also the class late_start.
1550 * At the moment, I've only put a few things in late_start that I know
1551 * are not needed to bring up the framework, and that also cause problems
1552 * with unmounting the tmpfs /data, but I hope to add add more services
1553 * to the late_start class as we optimize this to decrease the delay
1554 * till the user is asked for the password to the filesystem.
1555 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001556
Paul Lawrencef4faa572014-01-29 13:31:03 -08001557 /* The init files are setup to stop the class main when vold.decrypt is
1558 * set to trigger_reset_main.
1559 */
1560 property_set("vold.decrypt", "trigger_reset_main");
1561 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001562
Paul Lawrencef4faa572014-01-29 13:31:03 -08001563 /* Ugh, shutting down the framework is not synchronous, so until it
1564 * can be fixed, this horrible hack will wait a moment for it all to
1565 * shut down before proceeding. Without it, some devices cannot
1566 * restart the graphics services.
1567 */
1568 sleep(2);
1569 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001570
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001571 /* Now that the framework is shutdown, we should be able to umount()
1572 * the tmpfs filesystem, and mount the real one.
1573 */
1574
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001575 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1576 if (strlen(crypto_blkdev) == 0) {
1577 SLOGE("fs_crypto_blkdev not set\n");
1578 return -1;
1579 }
1580
Ken Sumralle5032c42012-04-01 23:58:44 -07001581 if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001582 /* If ro.crypto.readonly is set to 1, mount the decrypted
1583 * filesystem readonly. This is used when /data is mounted by
1584 * recovery mode.
1585 */
1586 char ro_prop[PROPERTY_VALUE_MAX];
1587 property_get("ro.crypto.readonly", ro_prop, "");
1588 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1589 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1590 rec->flags |= MS_RDONLY;
1591 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001592
Ken Sumralle5032c42012-04-01 23:58:44 -07001593 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001594 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, 0)) {
1595 SLOGE("Failed to mount decrypted data");
1596 cryptfs_set_corrupt();
1597 cryptfs_trigger_restart_min_framework();
1598 SLOGI("Started framework to offer wipe");
1599 return -1;
1600 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001601
Ken Sumralle5032c42012-04-01 23:58:44 -07001602 property_set("vold.decrypt", "trigger_load_persist_props");
1603 /* Create necessary paths on /data */
1604 if (prep_data_fs()) {
1605 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001606 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001607
1608 /* startup service classes main and late_start */
1609 property_set("vold.decrypt", "trigger_restart_framework");
1610 SLOGD("Just triggered restart_framework\n");
1611
1612 /* Give it a few moments to get started */
1613 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001614 }
1615
Ken Sumrall0cc16632011-01-18 20:32:26 -08001616 if (rc == 0) {
1617 restart_successful = 1;
1618 }
1619
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001620 return rc;
1621}
1622
Paul Lawrencef4faa572014-01-29 13:31:03 -08001623int cryptfs_restart(void)
1624{
1625 /* Call internal implementation forcing a restart of main service group */
1626 return cryptfs_restart_internal(1);
1627}
1628
Mark Salyzyn3e971272014-01-21 13:27:04 -08001629static int do_crypto_complete(char *mount_point UNUSED)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001630{
1631 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001632 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001633 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001634
1635 property_get("ro.crypto.state", encrypted_state, "");
1636 if (strcmp(encrypted_state, "encrypted") ) {
1637 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001638 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001639 }
1640
Ken Sumrall160b4d62013-04-22 12:15:39 -07001641 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001642 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001643
Ken Sumralle1a45852011-12-14 21:24:27 -08001644 /*
1645 * Only report this error if key_loc is a file and it exists.
1646 * If the device was never encrypted, and /data is not mountable for
1647 * some reason, returning 1 should prevent the UI from presenting the
1648 * a "enter password" screen, or worse, a "press button to wipe the
1649 * device" screen.
1650 */
1651 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1652 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001653 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001654 } else {
1655 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001656 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001657 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001658 }
1659
Paul Lawrence74f29f12014-08-28 15:54:10 -07001660 // Test for possible error flags
1661 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1662 SLOGE("Encryption process is partway completed\n");
1663 return CRYPTO_COMPLETE_PARTIAL;
1664 }
1665
1666 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1667 SLOGE("Encryption process was interrupted but cannot continue\n");
1668 return CRYPTO_COMPLETE_INCONSISTENT;
1669 }
1670
1671 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1672 SLOGE("Encryption is successful but data is corrupt\n");
1673 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001674 }
1675
1676 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001677 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001678}
1679
Paul Lawrencef4faa572014-01-29 13:31:03 -08001680static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1681 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001682{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001683 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001684 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001685 char crypto_blkdev[MAXPATHLEN];
1686 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001687 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001688 unsigned int orig_failed_decrypt_count;
1689 int rc;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001690 kdf_func kdf;
1691 void *kdf_params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001692 int use_keymaster = 0;
1693 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001694 unsigned char* intermediate_key = 0;
1695 size_t intermediate_key_size = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001696
Paul Lawrencef4faa572014-01-29 13:31:03 -08001697 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1698 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001699
Paul Lawrencef4faa572014-01-29 13:31:03 -08001700 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001701 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1702 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001703 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001704 rc = -1;
1705 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001706 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001707 }
1708
Paul Lawrencef4faa572014-01-29 13:31:03 -08001709 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1710
Paul Lawrence74f29f12014-08-28 15:54:10 -07001711 // Create crypto block device - all (non fatal) code paths
1712 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001713 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1714 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001715 SLOGE("Error creating decrypted block device\n");
1716 rc = -1;
1717 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001718 }
1719
Paul Lawrence74f29f12014-08-28 15:54:10 -07001720 /* Work out if the problem is the password or the data */
1721 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1722 scrypted_intermediate_key)];
1723 int N = 1 << crypt_ftr->N_factor;
1724 int r = 1 << crypt_ftr->r_factor;
1725 int p = 1 << crypt_ftr->p_factor;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001726
Paul Lawrence74f29f12014-08-28 15:54:10 -07001727 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1728 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1729 N, r, p, scrypted_intermediate_key,
1730 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001731
Paul Lawrence74f29f12014-08-28 15:54:10 -07001732 // Does the key match the crypto footer?
1733 if (rc == 0 && memcmp(scrypted_intermediate_key,
1734 crypt_ftr->scrypted_intermediate_key,
1735 sizeof(scrypted_intermediate_key)) == 0) {
1736 SLOGI("Password matches");
1737 rc = 0;
1738 } else {
1739 /* Try mounting the file system anyway, just in case the problem's with
1740 * the footer, not the key. */
1741 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1742 mkdir(tmp_mount_point, 0755);
1743 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1744 SLOGE("Error temp mounting decrypted block device\n");
1745 delete_crypto_blk_dev(label);
1746
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001747 rc = ++crypt_ftr->failed_decrypt_count;
1748 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001749 } else {
1750 /* Success! */
1751 SLOGI("Password did not match but decrypted drive mounted - continue");
1752 umount(tmp_mount_point);
1753 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001754 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001755 }
1756
1757 if (rc == 0) {
1758 crypt_ftr->failed_decrypt_count = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001759
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001760 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001761 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001762 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001763
1764 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001765 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001766 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001767 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001768 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001769 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001770 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001771
Paul Lawrence74f29f12014-08-28 15:54:10 -07001772 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001773 use_keymaster = keymaster_check_compatibility();
1774 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001775 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001776 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1777 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1778 upgrade = 1;
1779 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001780 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001781 upgrade = 1;
1782 }
1783
1784 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001785 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1786 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001787 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001788 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001789 }
1790 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001791
1792 // Do not fail even if upgrade failed - machine is bootable
1793 // Note that if this code is ever hit, there is a *serious* problem
1794 // since KDFs should never fail. You *must* fix the kdf before
1795 // proceeding!
1796 if (rc) {
1797 SLOGW("Upgrade failed with error %d,"
1798 " but continuing with previous state",
1799 rc);
1800 rc = 0;
1801 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001802 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001803 }
1804
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001805 errout:
1806 if (intermediate_key) {
1807 memset(intermediate_key, 0, intermediate_key_size);
1808 free(intermediate_key);
1809 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001810 return rc;
1811}
1812
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001813/* Called by vold when it wants to undo the crypto mapping of a volume it
1814 * manages. This is usually in response to a factory reset, when we want
1815 * to undo the crypto mapping so the volume is formatted in the clear.
1816 */
1817int cryptfs_revert_volume(const char *label)
1818{
1819 return delete_crypto_blk_dev((char *)label);
1820}
1821
Ken Sumrall29d8da82011-05-18 17:20:07 -07001822/*
1823 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1824 * Setup a dm-crypt mapping, use the saved master key from
1825 * setting up the /data mapping, and return the new device path.
1826 */
1827int cryptfs_setup_volume(const char *label, int major, int minor,
1828 char *crypto_sys_path, unsigned int max_path,
1829 int *new_major, int *new_minor)
1830{
1831 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1832 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001833 struct stat statbuf;
1834 int nr_sec, fd;
1835
1836 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1837
Ken Sumrall160b4d62013-04-22 12:15:39 -07001838 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001839
1840 /* Update the fs_size field to be the size of the volume */
1841 fd = open(real_blkdev, O_RDONLY);
1842 nr_sec = get_blkdev_size(fd);
1843 close(fd);
1844 if (nr_sec == 0) {
1845 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1846 return -1;
1847 }
1848
1849 sd_crypt_ftr.fs_size = nr_sec;
1850 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1851 crypto_blkdev, label);
1852
1853 stat(crypto_blkdev, &statbuf);
1854 *new_major = MAJOR(statbuf.st_rdev);
1855 *new_minor = MINOR(statbuf.st_rdev);
1856
1857 /* Create path to sys entry for this block device */
1858 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1859
1860 return 0;
1861}
1862
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001863int cryptfs_crypto_complete(void)
1864{
1865 return do_crypto_complete("/data");
1866}
1867
Paul Lawrencef4faa572014-01-29 13:31:03 -08001868int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1869{
1870 char encrypted_state[PROPERTY_VALUE_MAX];
1871 property_get("ro.crypto.state", encrypted_state, "");
1872 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1873 SLOGE("encrypted fs already validated or not running with encryption,"
1874 " aborting");
1875 return -1;
1876 }
1877
1878 if (get_crypt_ftr_and_key(crypt_ftr)) {
1879 SLOGE("Error getting crypt footer and key");
1880 return -1;
1881 }
1882
1883 return 0;
1884}
1885
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001886int cryptfs_check_passwd(char *passwd)
1887{
Paul Lawrencef4faa572014-01-29 13:31:03 -08001888 struct crypt_mnt_ftr crypt_ftr;
1889 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001890
Paul Lawrencef4faa572014-01-29 13:31:03 -08001891 rc = check_unmounted_and_get_ftr(&crypt_ftr);
1892 if (rc)
1893 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001894
Paul Lawrencef4faa572014-01-29 13:31:03 -08001895 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
1896 DATA_MNT_POINT, "userdata");
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001897
1898 if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001899 cryptfs_clear_password();
1900 password = strdup(passwd);
1901 struct timespec now;
1902 clock_gettime(CLOCK_BOOTTIME, &now);
1903 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001904 }
1905
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001906 return rc;
1907}
1908
Ken Sumrall3ad90722011-10-04 20:38:29 -07001909int cryptfs_verify_passwd(char *passwd)
1910{
1911 struct crypt_mnt_ftr crypt_ftr;
1912 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001913 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001914 char encrypted_state[PROPERTY_VALUE_MAX];
1915 int rc;
1916
1917 property_get("ro.crypto.state", encrypted_state, "");
1918 if (strcmp(encrypted_state, "encrypted") ) {
1919 SLOGE("device not encrypted, aborting");
1920 return -2;
1921 }
1922
1923 if (!master_key_saved) {
1924 SLOGE("encrypted fs not yet mounted, aborting");
1925 return -1;
1926 }
1927
1928 if (!saved_mount_point) {
1929 SLOGE("encrypted fs failed to save mount point, aborting");
1930 return -1;
1931 }
1932
Ken Sumrall160b4d62013-04-22 12:15:39 -07001933 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001934 SLOGE("Error getting crypt footer and key\n");
1935 return -1;
1936 }
1937
1938 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1939 /* If the device has no password, then just say the password is valid */
1940 rc = 0;
1941 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001942 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001943 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1944 /* They match, the password is correct */
1945 rc = 0;
1946 } else {
1947 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1948 sleep(1);
1949 rc = 1;
1950 }
1951 }
1952
1953 return rc;
1954}
1955
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001956/* Initialize a crypt_mnt_ftr structure. The keysize is
1957 * defaulted to 16 bytes, and the filesystem size to 0.
1958 * Presumably, at a minimum, the caller will update the
1959 * filesystem size and crypto_type_name after calling this function.
1960 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001961static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001962{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001963 off64_t off;
1964
1965 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001966 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001967 ftr->major_version = CURRENT_MAJOR_VERSION;
1968 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001969 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001970 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001971
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001972 switch (keymaster_check_compatibility()) {
1973 case 1:
1974 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1975 break;
1976
1977 case 0:
1978 ftr->kdf_type = KDF_SCRYPT;
1979 break;
1980
1981 default:
1982 SLOGE("keymaster_check_compatibility failed");
1983 return -1;
1984 }
1985
Kenny Rootc4c70f12013-06-14 12:11:38 -07001986 get_device_scrypt_params(ftr);
1987
Ken Sumrall160b4d62013-04-22 12:15:39 -07001988 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1989 if (get_crypt_ftr_info(NULL, &off) == 0) {
1990 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1991 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1992 ftr->persist_data_size;
1993 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001994
1995 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001996}
1997
Ken Sumrall29d8da82011-05-18 17:20:07 -07001998static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001999{
Ken Sumralle550f782013-08-20 13:48:23 -07002000 const char *args[10];
2001 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
2002 int num_args;
2003 int status;
2004 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002005 int rc = -1;
2006
Ken Sumrall29d8da82011-05-18 17:20:07 -07002007 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07002008 args[0] = "/system/bin/make_ext4fs";
2009 args[1] = "-a";
2010 args[2] = "/data";
2011 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07002012 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07002013 args[4] = size_str;
2014 args[5] = crypto_blkdev;
2015 num_args = 6;
2016 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
2017 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07002018 } else if (type == F2FS_FS) {
2019 args[0] = "/system/bin/mkfs.f2fs";
2020 args[1] = "-t";
2021 args[2] = "-d1";
2022 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07002023 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07002024 args[4] = size_str;
2025 num_args = 5;
2026 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
2027 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002028 } else {
2029 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
2030 return -1;
2031 }
2032
Ken Sumralle550f782013-08-20 13:48:23 -07002033 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
2034
2035 if (tmp != 0) {
2036 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002037 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07002038 if (WIFEXITED(status)) {
2039 if (WEXITSTATUS(status)) {
2040 SLOGE("Error creating filesystem on %s, exit status %d ",
2041 crypto_blkdev, WEXITSTATUS(status));
2042 } else {
2043 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
2044 rc = 0;
2045 }
2046 } else {
2047 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
2048 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002049 }
2050
2051 return rc;
2052}
2053
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002054#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08002055#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
2056#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002057
2058/* aligned 32K writes tends to make flash happy.
2059 * SD card association recommends it.
2060 */
2061#define BLOCKS_AT_A_TIME 8
2062
2063struct encryptGroupsData
2064{
2065 int realfd;
2066 int cryptofd;
2067 off64_t numblocks;
2068 off64_t one_pct, cur_pct, new_pct;
2069 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002070 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002071 char* real_blkdev, * crypto_blkdev;
2072 int count;
2073 off64_t offset;
2074 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08002075 off64_t last_written_sector;
2076 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002077 time_t time_started;
2078 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002079};
2080
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002081static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002082{
2083 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002084
2085 if (is_used) {
2086 data->used_blocks_already_done++;
2087 }
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002088 if (data->tot_used_blocks) {
2089 data->new_pct = data->used_blocks_already_done / data->one_pct;
2090 } else {
2091 data->new_pct = data->blocks_already_done / data->one_pct;
2092 }
2093
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002094 if (data->new_pct > data->cur_pct) {
2095 char buf[8];
2096 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07002097 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002098 property_set("vold.encrypt_progress", buf);
Elliott Hughescb33f572014-06-25 18:25:11 -07002099 SLOGI("Encrypted %" PRId64 " percent of drive", data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002100 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002101
2102 if (data->cur_pct >= 5) {
2103 double elapsed_time = difftime(time(NULL), data->time_started);
2104 off64_t remaining_blocks = data->tot_used_blocks
2105 - data->used_blocks_already_done;
2106 int remaining_time = (int)(elapsed_time * remaining_blocks
2107 / data->used_blocks_already_done);
Paul Lawrence71577502014-08-13 14:55:55 -07002108
2109 // Change time only if not yet set, lower, or a lot higher for
2110 // best user experience
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002111 if (data->remaining_time == -1
Paul Lawrence71577502014-08-13 14:55:55 -07002112 || remaining_time < data->remaining_time
2113 || remaining_time > data->remaining_time + 60) {
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002114 char buf[8];
2115 snprintf(buf, sizeof(buf), "%d", remaining_time);
2116 property_set("vold.encrypt_time_remaining", buf);
2117
Elliott Hughescb33f572014-06-25 18:25:11 -07002118 SLOGI("Encrypted %" PRId64 " percent of drive, %d seconds to go",
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002119 data->cur_pct, remaining_time);
2120 data->remaining_time = remaining_time;
2121 }
2122 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002123}
2124
2125static int flush_outstanding_data(struct encryptGroupsData* data)
2126{
2127 if (data->count == 0) {
2128 return 0;
2129 }
2130
Elliott Hughes231bdba2014-06-25 18:36:19 -07002131 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002132
2133 if (pread64(data->realfd, data->buffer,
2134 info.block_size * data->count, data->offset)
2135 <= 0) {
2136 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2137 data->real_blkdev);
2138 return -1;
2139 }
2140
2141 if (pwrite64(data->cryptofd, data->buffer,
2142 info.block_size * data->count, data->offset)
2143 <= 0) {
2144 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2145 data->crypto_blkdev);
2146 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002147 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002148 SLOGI("Encrypted %d blocks at sector %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002149 data->count, data->offset / info.block_size * CRYPT_SECTOR_SIZE);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002150 }
2151
2152 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002153 data->last_written_sector = (data->offset + data->count)
2154 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002155 return 0;
2156}
2157
2158static int encrypt_groups(struct encryptGroupsData* data)
2159{
2160 unsigned int i;
2161 u8 *block_bitmap = 0;
2162 unsigned int block;
2163 off64_t ret;
2164 int rc = -1;
2165
2166 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
2167 if (!data->buffer) {
2168 SLOGE("Failed to allocate crypto buffer");
2169 goto errout;
2170 }
2171
2172 block_bitmap = malloc(info.block_size);
2173 if (!block_bitmap) {
2174 SLOGE("failed to allocate block bitmap");
2175 goto errout;
2176 }
2177
2178 for (i = 0; i < aux_info.groups; ++i) {
2179 SLOGI("Encrypting group %d", i);
2180
2181 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2182 u32 block_count = min(info.blocks_per_group,
2183 aux_info.len_blocks - first_block);
2184
2185 off64_t offset = (u64)info.block_size
2186 * aux_info.bg_desc[i].bg_block_bitmap;
2187
2188 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2189 if (ret != (int)info.block_size) {
2190 SLOGE("failed to read all of block group bitmap %d", i);
2191 goto errout;
2192 }
2193
2194 offset = (u64)info.block_size * first_block;
2195
2196 data->count = 0;
2197
2198 for (block = 0; block < block_count; block++) {
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002199 int used = bitmap_get_bit(block_bitmap, block);
2200 update_progress(data, used);
2201 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002202 if (data->count == 0) {
2203 data->offset = offset;
2204 }
2205 data->count++;
2206 } else {
2207 if (flush_outstanding_data(data)) {
2208 goto errout;
2209 }
2210 }
2211
2212 offset += info.block_size;
2213
2214 /* Write data if we are aligned or buffer size reached */
2215 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2216 || data->count == BLOCKS_AT_A_TIME) {
2217 if (flush_outstanding_data(data)) {
2218 goto errout;
2219 }
2220 }
Paul Lawrence87999172014-02-20 12:21:31 -08002221
Paul Lawrence73d7a022014-06-09 14:10:09 -07002222 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002223 SLOGE("Stopping encryption due to low battery");
2224 rc = 0;
2225 goto errout;
2226 }
2227
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002228 }
2229 if (flush_outstanding_data(data)) {
2230 goto errout;
2231 }
2232 }
2233
Paul Lawrence87999172014-02-20 12:21:31 -08002234 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002235 rc = 0;
2236
2237errout:
2238 free(data->buffer);
2239 free(block_bitmap);
2240 return rc;
2241}
2242
2243static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2244 char *real_blkdev,
2245 off64_t size,
2246 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002247 off64_t tot_size,
2248 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002249{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002250 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002251 struct encryptGroupsData data;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002252 int rc; // Can't initialize without causing warning -Wclobbered
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002253
Paul Lawrence87999172014-02-20 12:21:31 -08002254 if (previously_encrypted_upto > *size_already_done) {
2255 SLOGD("Not fast encrypting since resuming part way through");
2256 return -1;
2257 }
2258
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002259 memset(&data, 0, sizeof(data));
2260 data.real_blkdev = real_blkdev;
2261 data.crypto_blkdev = crypto_blkdev;
2262
2263 if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
2264 SLOGE("Error opening real_blkdev %s for inplace encrypt\n",
2265 real_blkdev);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002266 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002267 goto errout;
2268 }
2269
2270 if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
2271 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n",
2272 crypto_blkdev);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002273 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002274 goto errout;
2275 }
2276
2277 if (setjmp(setjmp_env)) {
2278 SLOGE("Reading extent caused an exception");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002279 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002280 goto errout;
2281 }
2282
2283 if (read_ext(data.realfd, 0) != 0) {
2284 SLOGE("Failed to read extent");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002285 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002286 goto errout;
2287 }
2288
2289 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2290 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2291 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2292
2293 SLOGI("Encrypting filesystem in place...");
2294
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002295 data.tot_used_blocks = data.numblocks;
2296 for (i = 0; i < aux_info.groups; ++i) {
2297 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2298 }
2299
2300 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002301 data.cur_pct = 0;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002302 data.time_started = time(NULL);
2303 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002304
2305 rc = encrypt_groups(&data);
2306 if (rc) {
2307 SLOGE("Error encrypting groups");
2308 goto errout;
2309 }
2310
Paul Lawrence87999172014-02-20 12:21:31 -08002311 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002312 rc = 0;
2313
2314errout:
2315 close(data.realfd);
2316 close(data.cryptofd);
2317
2318 return rc;
2319}
2320
Daniel Rosenberge82df162014-08-15 22:19:23 +00002321static int encrypt_one_block_f2fs(u64 pos, void *data)
2322{
2323 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2324
2325 priv_dat->blocks_already_done = pos - 1;
2326 update_progress(priv_dat, 1);
2327
2328 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2329
2330 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
2331 SLOGE("Error reading real_blkdev %s for inplace encrypt", priv_dat->crypto_blkdev);
2332 return -1;
2333 }
2334
2335 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
2336 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", priv_dat->crypto_blkdev);
2337 return -1;
2338 } else {
2339 SLOGD("Encrypted block %"PRIu64, pos);
2340 }
2341
2342 return 0;
2343}
2344
2345static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2346 char *real_blkdev,
2347 off64_t size,
2348 off64_t *size_already_done,
2349 off64_t tot_size,
2350 off64_t previously_encrypted_upto)
2351{
2352 u32 i;
2353 struct encryptGroupsData data;
2354 struct f2fs_info *f2fs_info = NULL;
2355 int rc = -1;
2356 if (previously_encrypted_upto > *size_already_done) {
2357 SLOGD("Not fast encrypting since resuming part way through");
2358 return -1;
2359 }
2360 memset(&data, 0, sizeof(data));
2361 data.real_blkdev = real_blkdev;
2362 data.crypto_blkdev = crypto_blkdev;
2363 data.realfd = -1;
2364 data.cryptofd = -1;
2365 if ( (data.realfd = open64(real_blkdev, O_RDWR)) < 0) {
2366 SLOGE("Error opening real_blkdev %s for inplace encrypt\n",
2367 real_blkdev);
2368 goto errout;
2369 }
2370 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY)) < 0) {
2371 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n",
2372 crypto_blkdev);
2373 goto errout;
2374 }
2375
2376 f2fs_info = generate_f2fs_info(data.realfd);
2377 if (!f2fs_info)
2378 goto errout;
2379
2380 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2381 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2382 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2383
2384 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2385
2386 data.one_pct = data.tot_used_blocks / 100;
2387 data.cur_pct = 0;
2388 data.time_started = time(NULL);
2389 data.remaining_time = -1;
2390
2391 data.buffer = malloc(f2fs_info->block_size);
2392 if (!data.buffer) {
2393 SLOGE("Failed to allocate crypto buffer");
2394 goto errout;
2395 }
2396
2397 data.count = 0;
2398
2399 /* Currently, this either runs to completion, or hits a nonrecoverable error */
2400 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2401
2402 if (rc) {
2403 SLOGE("Error in running over blocks");
2404 goto errout;
2405 }
2406
2407 *size_already_done += size;
2408 rc = 0;
2409
2410errout:
2411 if (rc)
2412 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2413
2414 free(f2fs_info);
2415 free(data.buffer);
2416 close(data.realfd);
2417 close(data.cryptofd);
2418
2419 return rc;
2420}
2421
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002422static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2423 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002424 off64_t tot_size,
2425 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002426{
2427 int realfd, cryptofd;
2428 char *buf[CRYPT_INPLACE_BUFSIZE];
2429 int rc = -1;
2430 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002431 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002432 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002433
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002434 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
2435 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
2436 return -1;
2437 }
2438
2439 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
2440 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
2441 close(realfd);
2442 return -1;
2443 }
2444
2445 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2446 * The size passed in is the number of 512 byte sectors in the filesystem.
2447 * So compute the number of whole 4K blocks we should read/write,
2448 * and the remainder.
2449 */
2450 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2451 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002452 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2453 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002454
2455 SLOGE("Encrypting filesystem in place...");
2456
Paul Lawrence87999172014-02-20 12:21:31 -08002457 i = previously_encrypted_upto + 1 - *size_already_done;
2458
2459 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2460 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2461 goto errout;
2462 }
2463
2464 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2465 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2466 goto errout;
2467 }
2468
2469 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2470 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2471 SLOGE("Error reading initial sectors from real_blkdev %s for "
2472 "inplace encrypt\n", crypto_blkdev);
2473 goto errout;
2474 }
2475 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2476 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2477 "inplace encrypt\n", crypto_blkdev);
2478 goto errout;
2479 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002480 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002481 }
2482 }
2483
Ken Sumrall29d8da82011-05-18 17:20:07 -07002484 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002485 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002486 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002487 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002488 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002489 if (new_pct > cur_pct) {
2490 char buf[8];
2491
2492 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002493 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002494 property_set("vold.encrypt_progress", buf);
2495 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002496 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002497 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002498 goto errout;
2499 }
2500 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002501 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2502 goto errout;
2503 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002504 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002505 CRYPT_SECTORS_PER_BUFSIZE,
2506 i * CRYPT_SECTORS_PER_BUFSIZE);
2507 }
2508
Paul Lawrence73d7a022014-06-09 14:10:09 -07002509 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002510 SLOGE("Stopping encryption due to low battery");
2511 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2512 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002513 goto errout;
2514 }
2515 }
2516
2517 /* Do any remaining sectors */
2518 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002519 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2520 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002521 goto errout;
2522 }
Paul Lawrence87999172014-02-20 12:21:31 -08002523 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2524 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002525 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002526 } else {
2527 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002528 }
2529 }
2530
Ken Sumrall29d8da82011-05-18 17:20:07 -07002531 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002532 rc = 0;
2533
2534errout:
2535 close(realfd);
2536 close(cryptofd);
2537
2538 return rc;
2539}
2540
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002541static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2542 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002543 off64_t tot_size,
2544 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002545{
Paul Lawrence87999172014-02-20 12:21:31 -08002546 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002547 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002548 }
2549
2550 if (*size_already_done + size < previously_encrypted_upto) {
2551 *size_already_done += size;
2552 return 0;
2553 }
2554
Daniel Rosenberge82df162014-08-15 22:19:23 +00002555 /* TODO: identify filesystem type.
2556 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2557 * then we will drop down to cryptfs_enable_inplace_f2fs.
2558 * */
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002559 if (cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002560 size, size_already_done,
2561 tot_size, previously_encrypted_upto) == 0) {
2562 return 0;
2563 }
2564
2565 if (cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
2566 size, size_already_done,
2567 tot_size, previously_encrypted_upto) == 0) {
2568 return 0;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002569 }
2570
2571 return cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002572 size, size_already_done, tot_size,
2573 previously_encrypted_upto);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002574}
2575
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002576#define CRYPTO_ENABLE_WIPE 1
2577#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002578
2579#define FRAMEWORK_BOOT_WAIT 60
2580
Ken Sumrall29d8da82011-05-18 17:20:07 -07002581static inline int should_encrypt(struct volume_info *volume)
2582{
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002583 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
Ken Sumrall29d8da82011-05-18 17:20:07 -07002584 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
2585}
2586
Paul Lawrence87999172014-02-20 12:21:31 -08002587static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2588{
2589 int fd = open(filename, O_RDONLY);
2590 if (fd == -1) {
2591 SLOGE("Error opening file %s", filename);
2592 return -1;
2593 }
2594
2595 char block[CRYPT_INPLACE_BUFSIZE];
2596 memset(block, 0, sizeof(block));
2597 if (unix_read(fd, block, sizeof(block)) < 0) {
2598 SLOGE("Error reading file %s", filename);
2599 close(fd);
2600 return -1;
2601 }
2602
2603 close(fd);
2604
2605 SHA256_CTX c;
2606 SHA256_Init(&c);
2607 SHA256_Update(&c, block, sizeof(block));
2608 SHA256_Final(buf, &c);
2609
2610 return 0;
2611}
2612
JP Abgrall62c7af32014-06-16 13:01:23 -07002613static int get_fs_type(struct fstab_rec *rec)
2614{
2615 if (!strcmp(rec->fs_type, "ext4")) {
2616 return EXT4_FS;
2617 } else if (!strcmp(rec->fs_type, "f2fs")) {
2618 return F2FS_FS;
2619 } else {
2620 return -1;
2621 }
2622}
2623
Paul Lawrence87999172014-02-20 12:21:31 -08002624static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2625 char *crypto_blkdev, char *real_blkdev,
2626 int previously_encrypted_upto)
2627{
2628 off64_t cur_encryption_done=0, tot_encryption_size=0;
2629 int i, rc = -1;
2630
Paul Lawrence73d7a022014-06-09 14:10:09 -07002631 if (!is_battery_ok_to_start()) {
2632 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002633 return 0;
2634 }
2635
2636 /* The size of the userdata partition, and add in the vold volumes below */
2637 tot_encryption_size = crypt_ftr->fs_size;
2638
2639 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002640 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2641 int fs_type = get_fs_type(rec);
2642 if (fs_type < 0) {
2643 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2644 return -1;
2645 }
2646 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002647 } else if (how == CRYPTO_ENABLE_INPLACE) {
2648 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2649 crypt_ftr->fs_size, &cur_encryption_done,
2650 tot_encryption_size,
2651 previously_encrypted_upto);
2652
Paul Lawrence73d7a022014-06-09 14:10:09 -07002653 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002654 crypt_ftr->encrypted_upto = cur_encryption_done;
2655 }
2656
Paul Lawrence73d7a022014-06-09 14:10:09 -07002657 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002658 /* The inplace routine never actually sets the progress to 100% due
2659 * to the round down nature of integer division, so set it here */
2660 property_set("vold.encrypt_progress", "100");
2661 }
2662 } else {
2663 /* Shouldn't happen */
2664 SLOGE("cryptfs_enable: internal error, unknown option\n");
2665 rc = -1;
2666 }
2667
2668 return rc;
2669}
2670
Paul Lawrence13486032014-02-03 13:28:11 -08002671int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
2672 int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002673{
2674 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002675 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07002676 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002677 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07002678 int rc=-1, fd, i, ret;
Paul Lawrence87999172014-02-20 12:21:31 -08002679 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002680 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002681 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002682 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002683 char key_loc[PROPERTY_VALUE_MAX];
2684 char fuse_sdcard[PROPERTY_VALUE_MAX];
2685 char *sd_mnt_point;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002686 int num_vols;
2687 struct volume_info *vol_list = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002688 off64_t previously_encrypted_upto = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002689
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002690 if (!strcmp(howarg, "wipe")) {
2691 how = CRYPTO_ENABLE_WIPE;
2692 } else if (! strcmp(howarg, "inplace")) {
2693 how = CRYPTO_ENABLE_INPLACE;
2694 } else {
2695 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002696 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002697 }
2698
Paul Lawrence87999172014-02-20 12:21:31 -08002699 /* See if an encryption was underway and interrupted */
2700 if (how == CRYPTO_ENABLE_INPLACE
2701 && get_crypt_ftr_and_key(&crypt_ftr) == 0
2702 && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
2703 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2704 crypt_ftr.encrypted_upto = 0;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002705 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
2706
2707 /* At this point, we are in an inconsistent state. Until we successfully
2708 complete encryption, a reboot will leave us broken. So mark the
2709 encryption failed in case that happens.
2710 On successfully completing encryption, remove this flag */
2711 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2712
2713 put_crypt_ftr_and_key(&crypt_ftr);
Paul Lawrence87999172014-02-20 12:21:31 -08002714 }
2715
2716 property_get("ro.crypto.state", encrypted_state, "");
2717 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2718 SLOGE("Device is already running encrypted, aborting");
2719 goto error_unencrypted;
2720 }
2721
2722 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2723 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002724 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002725
Ken Sumrall3ed82362011-01-28 23:31:16 -08002726 /* Get the size of the real block device */
2727 fd = open(real_blkdev, O_RDONLY);
2728 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
2729 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2730 goto error_unencrypted;
2731 }
2732 close(fd);
2733
2734 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002735 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002736 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002737 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002738 if (fs_size_sec == 0)
2739 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2740
Paul Lawrence87999172014-02-20 12:21:31 -08002741 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002742
2743 if (fs_size_sec > max_fs_size_sec) {
2744 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2745 goto error_unencrypted;
2746 }
2747 }
2748
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002749 /* Get a wakelock as this may take a while, and we don't want the
2750 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2751 * wants to keep the screen on, it can grab a full wakelock.
2752 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002753 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002754 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2755
Jeff Sharkey7382f812012-08-23 14:08:59 -07002756 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07002757 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07002758 if (!sd_mnt_point) {
2759 sd_mnt_point = getenv("EXTERNAL_STORAGE");
2760 }
2761 if (!sd_mnt_point) {
2762 sd_mnt_point = "/mnt/sdcard";
2763 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07002764
Paul Lawrence87999172014-02-20 12:21:31 -08002765 /* TODO
2766 * Currently do not have test devices with multiple encryptable volumes.
2767 * When we acquire some, re-add support.
2768 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002769 num_vols=vold_getNumDirectVolumes();
2770 vol_list = malloc(sizeof(struct volume_info) * num_vols);
2771 vold_getDirectVolumeList(vol_list);
2772
2773 for (i=0; i<num_vols; i++) {
2774 if (should_encrypt(&vol_list[i])) {
Paul Lawrence87999172014-02-20 12:21:31 -08002775 SLOGE("Cannot encrypt if there are multiple encryptable volumes"
2776 "%s\n", vol_list[i].label);
2777 goto error_unencrypted;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002778 }
2779 }
2780
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002781 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002782 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002783 */
2784 property_set("vold.decrypt", "trigger_shutdown_framework");
2785 SLOGD("Just asked init to shut down class main\n");
2786
Ken Sumrall425524d2012-06-14 20:55:28 -07002787 if (vold_unmountAllAsecs()) {
2788 /* Just report the error. If any are left mounted,
2789 * umounting /data below will fail and handle the error.
2790 */
2791 SLOGE("Error unmounting internal asecs");
2792 }
2793
Ken Sumrall29d8da82011-05-18 17:20:07 -07002794 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
2795 if (!strcmp(fuse_sdcard, "true")) {
2796 /* This is a device using the fuse layer to emulate the sdcard semantics
2797 * on top of the userdata partition. vold does not manage it, it is managed
2798 * by the sdcard service. The sdcard service was killed by the property trigger
2799 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
2800 * unlike the case for vold managed devices above.
2801 */
2802 if (wait_and_unmount(sd_mnt_point)) {
2803 goto error_shutting_down;
2804 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002805 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002806
2807 /* Now unmount the /data partition. */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002808 if (wait_and_unmount(DATA_MNT_POINT)) {
JP Abgrall502dc742013-11-01 13:06:20 -07002809 if (allow_reboot) {
2810 goto error_shutting_down;
2811 } else {
2812 goto error_unencrypted;
2813 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002814 }
2815
2816 /* Do extra work for a better UX when doing the long inplace encryption */
2817 if (how == CRYPTO_ENABLE_INPLACE) {
2818 /* Now that /data is unmounted, we need to mount a tmpfs
2819 * /data, set a property saying we're doing inplace encryption,
2820 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002821 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002822 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002823 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002824 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002825 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002826 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002827
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002828 /* restart the framework. */
2829 /* Create necessary paths on /data */
2830 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002831 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002832 }
2833
Ken Sumrall92736ef2012-10-17 20:57:14 -07002834 /* Ugh, shutting down the framework is not synchronous, so until it
2835 * can be fixed, this horrible hack will wait a moment for it all to
2836 * shut down before proceeding. Without it, some devices cannot
2837 * restart the graphics services.
2838 */
2839 sleep(2);
2840
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002841 /* startup service classes main and late_start */
2842 property_set("vold.decrypt", "trigger_restart_min_framework");
2843 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002844
Ken Sumrall7df84122011-01-18 14:04:08 -08002845 /* OK, the framework is restarted and will soon be showing a
2846 * progress bar. Time to setup an encrypted mapping, and
2847 * either write a new filesystem, or encrypt in place updating
2848 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002849 */
2850 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002851
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002852 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002853 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence87999172014-02-20 12:21:31 -08002854 if (previously_encrypted_upto == 0) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002855 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2856 goto error_shutting_down;
2857 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002858
Paul Lawrence87999172014-02-20 12:21:31 -08002859 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2860 crypt_ftr.fs_size = nr_sec
2861 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2862 } else {
2863 crypt_ftr.fs_size = nr_sec;
2864 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002865 /* At this point, we are in an inconsistent state. Until we successfully
2866 complete encryption, a reboot will leave us broken. So mark the
2867 encryption failed in case that happens.
2868 On successfully completing encryption, remove this flag */
2869 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence87999172014-02-20 12:21:31 -08002870 crypt_ftr.crypt_type = crypt_type;
2871 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002872
Paul Lawrence87999172014-02-20 12:21:31 -08002873 /* Make an encrypted master key */
2874 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
2875 SLOGE("Cannot create encrypted master key\n");
2876 goto error_shutting_down;
2877 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002878
Paul Lawrence87999172014-02-20 12:21:31 -08002879 /* Write the key to the end of the partition */
2880 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002881
Paul Lawrence87999172014-02-20 12:21:31 -08002882 /* If any persistent data has been remembered, save it.
2883 * If none, create a valid empty table and save that.
2884 */
2885 if (!persist_data) {
2886 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
2887 if (pdata) {
2888 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2889 persist_data = pdata;
2890 }
2891 }
2892 if (persist_data) {
2893 save_persistent_data();
2894 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002895 }
2896
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002897 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002898 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
2899 "userdata");
2900
Paul Lawrence87999172014-02-20 12:21:31 -08002901 /* If we are continuing, check checksums match */
2902 rc = 0;
2903 if (previously_encrypted_upto) {
2904 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2905 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002906
Paul Lawrence87999172014-02-20 12:21:31 -08002907 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2908 sizeof(hash_first_block)) != 0) {
2909 SLOGE("Checksums do not match - trigger wipe");
2910 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002911 }
2912 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002913
Paul Lawrence87999172014-02-20 12:21:31 -08002914 if (!rc) {
2915 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
2916 crypto_blkdev, real_blkdev,
2917 previously_encrypted_upto);
2918 }
2919
2920 /* Calculate checksum if we are not finished */
Paul Lawrence73d7a022014-06-09 14:10:09 -07002921 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002922 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2923 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002924 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002925 SLOGE("Error calculating checksum for continuing encryption");
2926 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002927 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002928 }
2929
2930 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002931 delete_crypto_blk_dev("userdata");
Ken Sumrall29d8da82011-05-18 17:20:07 -07002932
2933 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002934
2935 if (! rc) {
2936 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002937 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002938
Paul Lawrence6bfed202014-07-28 12:47:22 -07002939 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002940 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2941 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002942 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002943 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002944
Paul Lawrence6bfed202014-07-28 12:47:22 -07002945 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002946
Paul Lawrence73d7a022014-06-09 14:10:09 -07002947 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002948 char value[PROPERTY_VALUE_MAX];
2949 property_get("ro.crypto.state", value, "");
2950 if (!strcmp(value, "")) {
2951 /* default encryption - continue first boot sequence */
2952 property_set("ro.crypto.state", "encrypted");
2953 release_wake_lock(lockid);
2954 cryptfs_check_passwd(DEFAULT_PASSWORD);
2955 cryptfs_restart_internal(1);
2956 return 0;
2957 } else {
2958 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08002959 cryptfs_reboot(reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002960 }
Paul Lawrence87999172014-02-20 12:21:31 -08002961 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002962 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Paul Lawrence87999172014-02-20 12:21:31 -08002963 cryptfs_reboot(shutdown);
2964 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002965 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002966 char value[PROPERTY_VALUE_MAX];
2967
Ken Sumrall319369a2012-06-27 16:30:18 -07002968 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002969 if (!strcmp(value, "1")) {
2970 /* wipe data if encryption failed */
2971 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
2972 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07002973 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002974 if (fd >= 0) {
2975 write(fd, "--wipe_data", strlen("--wipe_data") + 1);
2976 close(fd);
2977 } else {
2978 SLOGE("could not open /cache/recovery/command\n");
2979 }
Paul Lawrence87999172014-02-20 12:21:31 -08002980 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002981 } else {
2982 /* set property to trigger dialog */
2983 property_set("vold.encrypt_progress", "error_partially_encrypted");
2984 release_wake_lock(lockid);
2985 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002986 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002987 }
2988
Ken Sumrall3ed82362011-01-28 23:31:16 -08002989 /* hrm, the encrypt step claims success, but the reboot failed.
2990 * This should not happen.
2991 * Set the property and return. Hope the framework can deal with it.
2992 */
2993 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002994 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002995 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002996
2997error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07002998 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002999 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003000 if (lockid[0]) {
3001 release_wake_lock(lockid);
3002 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003003 return -1;
3004
3005error_shutting_down:
3006 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3007 * but the framework is stopped and not restarted to show the error, so it's up to
3008 * vold to restart the system.
3009 */
3010 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08003011 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003012
3013 /* shouldn't get here */
3014 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003015 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003016 if (lockid[0]) {
3017 release_wake_lock(lockid);
3018 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003019 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003020}
3021
Paul Lawrence45f10532014-04-04 18:11:56 +00003022int cryptfs_enable(char *howarg, int type, char *passwd, int allow_reboot)
Paul Lawrence13486032014-02-03 13:28:11 -08003023{
Paul Lawrence45f10532014-04-04 18:11:56 +00003024 return cryptfs_enable_internal(howarg, type, passwd, allow_reboot);
Paul Lawrence13486032014-02-03 13:28:11 -08003025}
3026
3027int cryptfs_enable_default(char *howarg, int allow_reboot)
3028{
3029 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
3030 DEFAULT_PASSWORD, allow_reboot);
3031}
3032
3033int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003034{
3035 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003036 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003037
3038 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003039 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003040 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003041 return -1;
3042 }
3043
Paul Lawrencef4faa572014-01-29 13:31:03 -08003044 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3045 SLOGE("Invalid crypt_type %d", crypt_type);
3046 return -1;
3047 }
3048
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003049 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003050 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003051 SLOGE("Error getting crypt footer and key");
3052 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003053 }
3054
Paul Lawrencef4faa572014-01-29 13:31:03 -08003055 crypt_ftr.crypt_type = crypt_type;
3056
3057 encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
3058 : newpw,
3059 crypt_ftr.salt,
3060 saved_master_key,
3061 crypt_ftr.master_key,
3062 &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003063
Jason parks70a4b3f2011-01-28 10:10:47 -06003064 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003065 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003066
3067 return 0;
3068}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003069
3070static int persist_get_key(char *fieldname, char *value)
3071{
3072 unsigned int i;
3073
3074 if (persist_data == NULL) {
3075 return -1;
3076 }
3077 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3078 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3079 /* We found it! */
3080 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3081 return 0;
3082 }
3083 }
3084
3085 return -1;
3086}
3087
3088static int persist_set_key(char *fieldname, char *value, int encrypted)
3089{
3090 unsigned int i;
3091 unsigned int num;
3092 struct crypt_mnt_ftr crypt_ftr;
3093 unsigned int max_persistent_entries;
3094 unsigned int dsize;
3095
3096 if (persist_data == NULL) {
3097 return -1;
3098 }
3099
3100 /* If encrypted, use the values from the crypt_ftr, otherwise
3101 * use the values for the current spec.
3102 */
3103 if (encrypted) {
3104 if(get_crypt_ftr_and_key(&crypt_ftr)) {
3105 return -1;
3106 }
3107 dsize = crypt_ftr.persist_data_size;
3108 } else {
3109 dsize = CRYPT_PERSIST_DATA_SIZE;
3110 }
3111 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3112 sizeof(struct crypt_persist_entry);
3113
3114 num = persist_data->persist_valid_entries;
3115
3116 for (i = 0; i < num; i++) {
3117 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3118 /* We found an existing entry, update it! */
3119 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3120 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3121 return 0;
3122 }
3123 }
3124
3125 /* We didn't find it, add it to the end, if there is room */
3126 if (persist_data->persist_valid_entries < max_persistent_entries) {
3127 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3128 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3129 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3130 persist_data->persist_valid_entries++;
3131 return 0;
3132 }
3133
3134 return -1;
3135}
3136
3137/* Return the value of the specified field. */
3138int cryptfs_getfield(char *fieldname, char *value, int len)
3139{
3140 char temp_value[PROPERTY_VALUE_MAX];
3141 char real_blkdev[MAXPATHLEN];
3142 /* 0 is success, 1 is not encrypted,
3143 * -1 is value not set, -2 is any other error
3144 */
3145 int rc = -2;
3146
3147 if (persist_data == NULL) {
3148 load_persistent_data();
3149 if (persist_data == NULL) {
3150 SLOGE("Getfield error, cannot load persistent data");
3151 goto out;
3152 }
3153 }
3154
3155 if (!persist_get_key(fieldname, temp_value)) {
3156 /* We found it, copy it to the caller's buffer and return */
3157 strlcpy(value, temp_value, len);
3158 rc = 0;
3159 } else {
3160 /* Sadness, it's not there. Return the error */
3161 rc = -1;
3162 }
3163
3164out:
3165 return rc;
3166}
3167
3168/* Set the value of the specified field. */
3169int cryptfs_setfield(char *fieldname, char *value)
3170{
3171 struct crypt_persist_data stored_pdata;
3172 struct crypt_persist_data *pdata_p;
3173 struct crypt_mnt_ftr crypt_ftr;
3174 char encrypted_state[PROPERTY_VALUE_MAX];
3175 /* 0 is success, -1 is an error */
3176 int rc = -1;
3177 int encrypted = 0;
3178
3179 if (persist_data == NULL) {
3180 load_persistent_data();
3181 if (persist_data == NULL) {
3182 SLOGE("Setfield error, cannot load persistent data");
3183 goto out;
3184 }
3185 }
3186
3187 property_get("ro.crypto.state", encrypted_state, "");
3188 if (!strcmp(encrypted_state, "encrypted") ) {
3189 encrypted = 1;
3190 }
3191
3192 if (persist_set_key(fieldname, value, encrypted)) {
3193 goto out;
3194 }
3195
3196 /* If we are running encrypted, save the persistent data now */
3197 if (encrypted) {
3198 if (save_persistent_data()) {
3199 SLOGE("Setfield error, cannot save persistent data");
3200 goto out;
3201 }
3202 }
3203
3204 rc = 0;
3205
3206out:
3207 return rc;
3208}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003209
3210/* Checks userdata. Attempt to mount the volume if default-
3211 * encrypted.
3212 * On success trigger next init phase and return 0.
3213 * Currently do not handle failure - see TODO below.
3214 */
3215int cryptfs_mount_default_encrypted(void)
3216{
3217 char decrypt_state[PROPERTY_VALUE_MAX];
3218 property_get("vold.decrypt", decrypt_state, "0");
3219 if (!strcmp(decrypt_state, "0")) {
3220 SLOGE("Not encrypted - should not call here");
3221 } else {
3222 int crypt_type = cryptfs_get_password_type();
3223 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3224 SLOGE("Bad crypt type - error");
3225 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3226 SLOGD("Password is not default - "
3227 "starting min framework to prompt");
3228 property_set("vold.decrypt", "trigger_restart_min_framework");
3229 return 0;
3230 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3231 SLOGD("Password is default - restarting filesystem");
3232 cryptfs_restart_internal(0);
3233 return 0;
3234 } else {
3235 SLOGE("Encrypted, default crypt type but can't decrypt");
3236 }
3237 }
3238
Paul Lawrence6bfed202014-07-28 12:47:22 -07003239 /** Corrupt. Allow us to boot into framework, which will detect bad
3240 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003241 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003242 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003243 return 0;
3244}
3245
3246/* Returns type of the password, default, pattern, pin or password.
3247 */
3248int cryptfs_get_password_type(void)
3249{
3250 struct crypt_mnt_ftr crypt_ftr;
3251
3252 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3253 SLOGE("Error getting crypt footer and key\n");
3254 return -1;
3255 }
3256
Paul Lawrence6bfed202014-07-28 12:47:22 -07003257 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3258 return -1;
3259 }
3260
Paul Lawrencef4faa572014-01-29 13:31:03 -08003261 return crypt_ftr.crypt_type;
3262}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003263
Paul Lawrence399317e2014-03-10 13:20:50 -07003264char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003265{
Paul Lawrence399317e2014-03-10 13:20:50 -07003266 struct timespec now;
3267 clock_gettime(CLOCK_MONOTONIC, &now);
3268 if (now.tv_sec < password_expiry_time) {
3269 return password;
3270 } else {
3271 cryptfs_clear_password();
3272 return 0;
3273 }
3274}
3275
3276void cryptfs_clear_password()
3277{
3278 if (password) {
3279 size_t len = strlen(password);
3280 memset(password, 0, len);
3281 free(password);
3282 password = 0;
3283 password_expiry_time = 0;
3284 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003285}