blob: 064823189b77d40dbac825cb7462bae65d68d947 [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>
28#include <unistd.h>
29#include <stdio.h>
30#include <sys/ioctl.h>
31#include <linux/dm-ioctl.h>
32#include <libgen.h>
33#include <stdlib.h>
34#include <sys/param.h>
35#include <string.h>
36#include <sys/mount.h>
37#include <openssl/evp.h>
38#include <errno.h>
Ken Sumrall3ed82362011-01-28 23:31:16 -080039#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070040#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070041#include <fs_mgr.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080042#include "cryptfs.h"
43#define LOG_TAG "Cryptfs"
44#include "cutils/log.h"
45#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070046#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080047#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070048#include <logwrap/logwrap.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070049#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070050#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070051#include "crypto_scrypt.h"
Paul Lawrenceae59fe62014-01-21 08:23:27 -080052#include "ext4_utils.h"
Paul Lawrence87999172014-02-20 12:21:31 -080053#include "CheckBattery.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080054
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070055#include <hardware/keymaster.h>
56
Mark Salyzyn3e971272014-01-21 13:27:04 -080057#define UNUSED __attribute__((unused))
58
Mark Salyzyn5eecc442014-02-12 14:16:14 -080059#define UNUSED __attribute__((unused))
60
Ken Sumrall8f869aa2010-12-03 03:47:09 -080061#define DM_CRYPT_BUF_SIZE 4096
62
Jason parks70a4b3f2011-01-28 10:10:47 -060063#define HASH_COUNT 2000
64#define KEY_LEN_BYTES 16
65#define IV_LEN_BYTES 16
66
Ken Sumrall29d8da82011-05-18 17:20:07 -070067#define KEY_IN_FOOTER "footer"
68
Paul Lawrencef4faa572014-01-29 13:31:03 -080069// "default_password" encoded into hex (d=0x64 etc)
70#define DEFAULT_PASSWORD "64656661756c745f70617373776f7264"
71
Ken Sumrall29d8da82011-05-18 17:20:07 -070072#define EXT4_FS 1
73#define FAT_FS 2
74
Ken Sumralle919efe2012-09-29 17:07:41 -070075#define TABLE_LOAD_RETRIES 10
76
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070077#define RSA_DEFAULT_KEY_SIZE 2048
78#define RSA_DEFAULT_EXPONENT 0x10001
79
Ken Sumrall8f869aa2010-12-03 03:47:09 -080080char *me = "cryptfs";
81
Jason parks70a4b3f2011-01-28 10:10:47 -060082static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070083static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060084static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -070085static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -080086
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070087static int keymaster_init(keymaster_device_t **keymaster_dev)
88{
89 int rc;
90
91 const hw_module_t* mod;
92 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
93 if (rc) {
94 ALOGE("could not find any keystore module");
95 goto out;
96 }
97
98 rc = keymaster_open(mod, keymaster_dev);
99 if (rc) {
100 ALOGE("could not open keymaster device in %s (%s)",
101 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
102 goto out;
103 }
104
105 return 0;
106
107out:
108 *keymaster_dev = NULL;
109 return rc;
110}
111
112/* Should we use keymaster? */
113static int keymaster_check_compatibility()
114{
115 keymaster_device_t *keymaster_dev = 0;
116 int rc = 0;
117
118 if (keymaster_init(&keymaster_dev)) {
119 SLOGE("Failed to init keymaster");
120 rc = -1;
121 goto out;
122 }
123
Paul Lawrence8c008392014-05-06 14:02:48 -0700124 SLOGI("keymaster version is %d", keymaster_dev->common.module->module_api_version);
125
126 if (keymaster_dev->common.module->module_api_version
127 < KEYMASTER_MODULE_API_VERSION_0_3) {
128 rc = 0;
129 goto out;
130 }
131
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700132 if (keymaster_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE) {
133 rc = 1;
134 }
135
136out:
137 keymaster_close(keymaster_dev);
138 return rc;
139}
140
141/* Create a new keymaster key and store it in this footer */
142static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
143{
144 uint8_t* key = 0;
145 keymaster_device_t *keymaster_dev = 0;
146
147 if (keymaster_init(&keymaster_dev)) {
148 SLOGE("Failed to init keymaster");
149 return -1;
150 }
151
152 int rc = 0;
153
154 keymaster_rsa_keygen_params_t params;
155 memset(&params, '\0', sizeof(params));
156 params.public_exponent = RSA_DEFAULT_EXPONENT;
157 params.modulus_size = RSA_DEFAULT_KEY_SIZE;
158
159 size_t key_size;
160 if (keymaster_dev->generate_keypair(keymaster_dev, TYPE_RSA, &params,
161 &key, &key_size)) {
162 SLOGE("Failed to generate keypair");
163 rc = -1;
164 goto out;
165 }
166
167 if (key_size > KEYMASTER_BLOB_SIZE) {
168 SLOGE("Keymaster key too large for crypto footer");
169 rc = -1;
170 goto out;
171 }
172
173 memcpy(ftr->keymaster_blob, key, key_size);
174 ftr->keymaster_blob_size = key_size;
175
176out:
177 keymaster_close(keymaster_dev);
178 free(key);
179 return rc;
180}
181
182/* This signs the given object using the keymaster key */
183static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
184 const unsigned char *object,
185 const size_t object_size,
186 unsigned char **signature,
187 size_t *signature_size)
188{
189 int rc = 0;
190 keymaster_device_t *keymaster_dev = 0;
191 if (keymaster_init(&keymaster_dev)) {
192 SLOGE("Failed to init keymaster");
193 return -1;
194 }
195
196 /* We currently set the digest type to DIGEST_NONE because it's the
197 * only supported value for keymaster. A similar issue exists with
198 * PADDING_NONE. Long term both of these should likely change.
199 */
200 keymaster_rsa_sign_params_t params;
201 params.digest_type = DIGEST_NONE;
202 params.padding_type = PADDING_NONE;
203
204 rc = keymaster_dev->sign_data(keymaster_dev,
205 &params,
206 ftr->keymaster_blob,
207 ftr->keymaster_blob_size,
208 object,
209 object_size,
210 signature,
211 signature_size);
212
213 keymaster_close(keymaster_dev);
214 return rc;
215}
216
Paul Lawrence399317e2014-03-10 13:20:50 -0700217/* Store password when userdata is successfully decrypted and mounted.
218 * Cleared by cryptfs_clear_password
219 *
220 * To avoid a double prompt at boot, we need to store the CryptKeeper
221 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
222 * Since the entire framework is torn down and rebuilt after encryption,
223 * we have to use a daemon or similar to store the password. Since vold
224 * is secured against IPC except from system processes, it seems a reasonable
225 * place to store this.
226 *
227 * password should be cleared once it has been used.
228 *
229 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800230 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700231static char* password = 0;
232static int password_expiry_time = 0;
233static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800234
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800235extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800236
Paul Lawrence87999172014-02-20 12:21:31 -0800237enum RebootType {reboot, recovery, shutdown};
238static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700239{
Paul Lawrence87999172014-02-20 12:21:31 -0800240 switch(rt) {
241 case reboot:
242 property_set(ANDROID_RB_PROPERTY, "reboot");
243 break;
244
245 case recovery:
246 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
247 break;
248
249 case shutdown:
250 property_set(ANDROID_RB_PROPERTY, "shutdown");
251 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700252 }
Paul Lawrence87999172014-02-20 12:21:31 -0800253
Ken Sumralladfba362013-06-04 16:37:52 -0700254 sleep(20);
255
256 /* Shouldn't get here, reboot should happen before sleep times out */
257 return;
258}
259
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800260static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
261{
262 memset(io, 0, dataSize);
263 io->data_size = dataSize;
264 io->data_start = sizeof(struct dm_ioctl);
265 io->version[0] = 4;
266 io->version[1] = 0;
267 io->version[2] = 0;
268 io->flags = flags;
269 if (name) {
270 strncpy(io->name, name, sizeof(io->name));
271 }
272}
273
Kenny Rootc4c70f12013-06-14 12:11:38 -0700274/**
275 * Gets the default device scrypt parameters for key derivation time tuning.
276 * The parameters should lead to about one second derivation time for the
277 * given device.
278 */
279static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
280 const int default_params[] = SCRYPT_DEFAULTS;
281 int params[] = SCRYPT_DEFAULTS;
282 char paramstr[PROPERTY_VALUE_MAX];
283 char *token;
284 char *saveptr;
285 int i;
286
287 property_get(SCRYPT_PROP, paramstr, "");
288 if (paramstr[0] != '\0') {
289 /*
290 * The token we're looking for should be three integers separated by
291 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
292 */
Kenny Root2947e342013-08-14 15:54:49 -0700293 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
294 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700295 i++, token = strtok_r(NULL, ":", &saveptr)) {
296 char *endptr;
297 params[i] = strtol(token, &endptr, 10);
298
299 /*
300 * Check that there was a valid number and it's 8-bit. If not,
301 * break out and the end check will take the default values.
302 */
303 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
304 break;
305 }
306 }
307
308 /*
309 * If there were not enough tokens or a token was malformed (not an
310 * integer), it will end up here and the default parameters can be
311 * taken.
312 */
313 if ((i != 3) || (token != NULL)) {
314 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
315 memcpy(params, default_params, sizeof(params));
316 }
317 }
318
319 ftr->N_factor = params[0];
320 ftr->r_factor = params[1];
321 ftr->p_factor = params[2];
322}
323
Ken Sumrall3ed82362011-01-28 23:31:16 -0800324static unsigned int get_fs_size(char *dev)
325{
326 int fd, block_size;
327 struct ext4_super_block sb;
328 off64_t len;
329
330 if ((fd = open(dev, O_RDONLY)) < 0) {
331 SLOGE("Cannot open device to get filesystem size ");
332 return 0;
333 }
334
335 if (lseek64(fd, 1024, SEEK_SET) < 0) {
336 SLOGE("Cannot seek to superblock");
337 return 0;
338 }
339
340 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
341 SLOGE("Cannot read superblock");
342 return 0;
343 }
344
345 close(fd);
346
347 block_size = 1024 << sb.s_log_block_size;
348 /* compute length in bytes */
349 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
350
351 /* return length in sectors */
352 return (unsigned int) (len / 512);
353}
354
Ken Sumrall160b4d62013-04-22 12:15:39 -0700355static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
356{
357 static int cached_data = 0;
358 static off64_t cached_off = 0;
359 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
360 int fd;
361 char key_loc[PROPERTY_VALUE_MAX];
362 char real_blkdev[PROPERTY_VALUE_MAX];
363 unsigned int nr_sec;
364 int rc = -1;
365
366 if (!cached_data) {
367 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
368
369 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
370 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
371 SLOGE("Cannot open real block device %s\n", real_blkdev);
372 return -1;
373 }
374
375 if ((nr_sec = get_blkdev_size(fd))) {
376 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
377 * encryption info footer and key, and plenty of bytes to spare for future
378 * growth.
379 */
380 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
381 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
382 cached_data = 1;
383 } else {
384 SLOGE("Cannot get size of block device %s\n", real_blkdev);
385 }
386 close(fd);
387 } else {
388 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
389 cached_off = 0;
390 cached_data = 1;
391 }
392 }
393
394 if (cached_data) {
395 if (metadata_fname) {
396 *metadata_fname = cached_metadata_fname;
397 }
398 if (off) {
399 *off = cached_off;
400 }
401 rc = 0;
402 }
403
404 return rc;
405}
406
Ken Sumralle8744072011-01-18 22:01:55 -0800407/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800408 * update the failed mount count but not change the key.
409 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700410static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800411{
412 int fd;
413 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700414 /* starting_off is set to the SEEK_SET offset
415 * where the crypto structure starts
416 */
417 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800418 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700419 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700420 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800421
Ken Sumrall160b4d62013-04-22 12:15:39 -0700422 if (get_crypt_ftr_info(&fname, &starting_off)) {
423 SLOGE("Unable to get crypt_ftr_info\n");
424 return -1;
425 }
426 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700427 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700428 return -1;
429 }
Ken Sumralle550f782013-08-20 13:48:23 -0700430 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
431 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700432 return -1;
433 }
434
435 /* Seek to the start of the crypt footer */
436 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
437 SLOGE("Cannot seek to real block device footer\n");
438 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800439 }
440
441 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
442 SLOGE("Cannot write real block device footer\n");
443 goto errout;
444 }
445
Ken Sumrall3be890f2011-09-14 16:53:46 -0700446 fstat(fd, &statbuf);
447 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700448 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700449 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800450 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800451 goto errout;
452 }
453 }
454
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800455 /* Success! */
456 rc = 0;
457
458errout:
459 close(fd);
460 return rc;
461
462}
463
Ken Sumrall160b4d62013-04-22 12:15:39 -0700464static inline int unix_read(int fd, void* buff, int len)
465{
466 return TEMP_FAILURE_RETRY(read(fd, buff, len));
467}
468
469static inline int unix_write(int fd, const void* buff, int len)
470{
471 return TEMP_FAILURE_RETRY(write(fd, buff, len));
472}
473
474static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
475{
476 memset(pdata, 0, len);
477 pdata->persist_magic = PERSIST_DATA_MAGIC;
478 pdata->persist_valid_entries = 0;
479}
480
481/* A routine to update the passed in crypt_ftr to the lastest version.
482 * fd is open read/write on the device that holds the crypto footer and persistent
483 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
484 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
485 */
486static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
487{
Kenny Root7434b312013-06-14 11:29:53 -0700488 int orig_major = crypt_ftr->major_version;
489 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700490
Kenny Root7434b312013-06-14 11:29:53 -0700491 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
492 struct crypt_persist_data *pdata;
493 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700494
Kenny Rootc4c70f12013-06-14 12:11:38 -0700495 SLOGW("upgrading crypto footer to 1.1");
496
Kenny Root7434b312013-06-14 11:29:53 -0700497 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
498 if (pdata == NULL) {
499 SLOGE("Cannot allocate persisent data\n");
500 return;
501 }
502 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
503
504 /* Need to initialize the persistent data area */
505 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
506 SLOGE("Cannot seek to persisent data offset\n");
507 return;
508 }
509 /* Write all zeros to the first copy, making it invalid */
510 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
511
512 /* Write a valid but empty structure to the second copy */
513 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
514 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
515
516 /* Update the footer */
517 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
518 crypt_ftr->persist_data_offset[0] = pdata_offset;
519 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
520 crypt_ftr->minor_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700521 }
522
Paul Lawrencef4faa572014-01-29 13:31:03 -0800523 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700524 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800525 /* But keep the old kdf_type.
526 * It will get updated later to KDF_SCRYPT after the password has been verified.
527 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700528 crypt_ftr->kdf_type = KDF_PBKDF2;
529 get_device_scrypt_params(crypt_ftr);
530 crypt_ftr->minor_version = 2;
531 }
532
Paul Lawrencef4faa572014-01-29 13:31:03 -0800533 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
534 SLOGW("upgrading crypto footer to 1.3");
535 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
536 crypt_ftr->minor_version = 3;
537 }
538
Kenny Root7434b312013-06-14 11:29:53 -0700539 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
540 if (lseek64(fd, offset, SEEK_SET) == -1) {
541 SLOGE("Cannot seek to crypt footer\n");
542 return;
543 }
544 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700545 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700546}
547
548
549static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800550{
551 int fd;
552 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700553 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800554 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700555 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700556 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800557
Ken Sumrall160b4d62013-04-22 12:15:39 -0700558 if (get_crypt_ftr_info(&fname, &starting_off)) {
559 SLOGE("Unable to get crypt_ftr_info\n");
560 return -1;
561 }
562 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700563 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700564 return -1;
565 }
566 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700567 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700568 return -1;
569 }
570
571 /* Make sure it's 16 Kbytes in length */
572 fstat(fd, &statbuf);
573 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
574 SLOGE("footer file %s is not the expected size!\n", fname);
575 goto errout;
576 }
577
578 /* Seek to the start of the crypt footer */
579 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
580 SLOGE("Cannot seek to real block device footer\n");
581 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800582 }
583
584 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
585 SLOGE("Cannot read real block device footer\n");
586 goto errout;
587 }
588
589 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700590 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800591 goto errout;
592 }
593
Kenny Rootc96a5f82013-06-14 12:08:28 -0700594 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
595 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
596 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800597 goto errout;
598 }
599
Kenny Rootc96a5f82013-06-14 12:08:28 -0700600 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
601 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
602 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800603 }
604
Ken Sumrall160b4d62013-04-22 12:15:39 -0700605 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
606 * copy on disk before returning.
607 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700608 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700609 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800610 }
611
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800612 /* Success! */
613 rc = 0;
614
615errout:
616 close(fd);
617 return rc;
618}
619
Ken Sumrall160b4d62013-04-22 12:15:39 -0700620static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
621{
622 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
623 crypt_ftr->persist_data_offset[1]) {
624 SLOGE("Crypt_ftr persist data regions overlap");
625 return -1;
626 }
627
628 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
629 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
630 return -1;
631 }
632
633 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
634 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
635 CRYPT_FOOTER_OFFSET) {
636 SLOGE("Persistent data extends past crypto footer");
637 return -1;
638 }
639
640 return 0;
641}
642
643static int load_persistent_data(void)
644{
645 struct crypt_mnt_ftr crypt_ftr;
646 struct crypt_persist_data *pdata = NULL;
647 char encrypted_state[PROPERTY_VALUE_MAX];
648 char *fname;
649 int found = 0;
650 int fd;
651 int ret;
652 int i;
653
654 if (persist_data) {
655 /* Nothing to do, we've already loaded or initialized it */
656 return 0;
657 }
658
659
660 /* If not encrypted, just allocate an empty table and initialize it */
661 property_get("ro.crypto.state", encrypted_state, "");
662 if (strcmp(encrypted_state, "encrypted") ) {
663 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
664 if (pdata) {
665 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
666 persist_data = pdata;
667 return 0;
668 }
669 return -1;
670 }
671
672 if(get_crypt_ftr_and_key(&crypt_ftr)) {
673 return -1;
674 }
675
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700676 if ((crypt_ftr.major_version < 1)
677 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700678 SLOGE("Crypt_ftr version doesn't support persistent data");
679 return -1;
680 }
681
682 if (get_crypt_ftr_info(&fname, NULL)) {
683 return -1;
684 }
685
686 ret = validate_persistent_data_storage(&crypt_ftr);
687 if (ret) {
688 return -1;
689 }
690
691 fd = open(fname, O_RDONLY);
692 if (fd < 0) {
693 SLOGE("Cannot open %s metadata file", fname);
694 return -1;
695 }
696
697 if (persist_data == NULL) {
698 pdata = malloc(crypt_ftr.persist_data_size);
699 if (pdata == NULL) {
700 SLOGE("Cannot allocate memory for persistent data");
701 goto err;
702 }
703 }
704
705 for (i = 0; i < 2; i++) {
706 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
707 SLOGE("Cannot seek to read persistent data on %s", fname);
708 goto err2;
709 }
710 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
711 SLOGE("Error reading persistent data on iteration %d", i);
712 goto err2;
713 }
714 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
715 found = 1;
716 break;
717 }
718 }
719
720 if (!found) {
721 SLOGI("Could not find valid persistent data, creating");
722 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
723 }
724
725 /* Success */
726 persist_data = pdata;
727 close(fd);
728 return 0;
729
730err2:
731 free(pdata);
732
733err:
734 close(fd);
735 return -1;
736}
737
738static int save_persistent_data(void)
739{
740 struct crypt_mnt_ftr crypt_ftr;
741 struct crypt_persist_data *pdata;
742 char *fname;
743 off64_t write_offset;
744 off64_t erase_offset;
745 int found = 0;
746 int fd;
747 int ret;
748
749 if (persist_data == NULL) {
750 SLOGE("No persistent data to save");
751 return -1;
752 }
753
754 if(get_crypt_ftr_and_key(&crypt_ftr)) {
755 return -1;
756 }
757
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700758 if ((crypt_ftr.major_version < 1)
759 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700760 SLOGE("Crypt_ftr version doesn't support persistent data");
761 return -1;
762 }
763
764 ret = validate_persistent_data_storage(&crypt_ftr);
765 if (ret) {
766 return -1;
767 }
768
769 if (get_crypt_ftr_info(&fname, NULL)) {
770 return -1;
771 }
772
773 fd = open(fname, O_RDWR);
774 if (fd < 0) {
775 SLOGE("Cannot open %s metadata file", fname);
776 return -1;
777 }
778
779 pdata = malloc(crypt_ftr.persist_data_size);
780 if (pdata == NULL) {
781 SLOGE("Cannot allocate persistant data");
782 goto err;
783 }
784
785 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
786 SLOGE("Cannot seek to read persistent data on %s", fname);
787 goto err2;
788 }
789
790 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
791 SLOGE("Error reading persistent data before save");
792 goto err2;
793 }
794
795 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
796 /* The first copy is the curent valid copy, so write to
797 * the second copy and erase this one */
798 write_offset = crypt_ftr.persist_data_offset[1];
799 erase_offset = crypt_ftr.persist_data_offset[0];
800 } else {
801 /* The second copy must be the valid copy, so write to
802 * the first copy, and erase the second */
803 write_offset = crypt_ftr.persist_data_offset[0];
804 erase_offset = crypt_ftr.persist_data_offset[1];
805 }
806
807 /* Write the new copy first, if successful, then erase the old copy */
808 if (lseek(fd, write_offset, SEEK_SET) < 0) {
809 SLOGE("Cannot seek to write persistent data");
810 goto err2;
811 }
812 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
813 (int) crypt_ftr.persist_data_size) {
814 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
815 SLOGE("Cannot seek to erase previous persistent data");
816 goto err2;
817 }
818 fsync(fd);
819 memset(pdata, 0, crypt_ftr.persist_data_size);
820 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
821 (int) crypt_ftr.persist_data_size) {
822 SLOGE("Cannot write to erase previous persistent data");
823 goto err2;
824 }
825 fsync(fd);
826 } else {
827 SLOGE("Cannot write to save persistent data");
828 goto err2;
829 }
830
831 /* Success */
832 free(pdata);
833 close(fd);
834 return 0;
835
836err2:
837 free(pdata);
838err:
839 close(fd);
840 return -1;
841}
842
Paul Lawrencef4faa572014-01-29 13:31:03 -0800843static int hexdigit (char c)
844{
845 if (c >= '0' && c <= '9') return c - '0';
846 c = tolower(c);
847 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
848 return -1;
849}
850
851static unsigned char* convert_hex_ascii_to_key(const char* master_key_ascii,
852 unsigned int* out_keysize)
853{
854 unsigned int i;
855 *out_keysize = 0;
856
857 size_t size = strlen (master_key_ascii);
858 if (size % 2) {
859 SLOGE("Trying to convert ascii string of odd length");
860 return NULL;
861 }
862
863 unsigned char* master_key = (unsigned char*) malloc(size / 2);
864 if (master_key == 0) {
865 SLOGE("Cannot allocate");
866 return NULL;
867 }
868
869 for (i = 0; i < size; i += 2) {
870 int high_nibble = hexdigit (master_key_ascii[i]);
871 int low_nibble = hexdigit (master_key_ascii[i + 1]);
872
873 if(high_nibble < 0 || low_nibble < 0) {
874 SLOGE("Invalid hex string");
875 free (master_key);
876 return NULL;
877 }
878
879 master_key[*out_keysize] = high_nibble * 16 + low_nibble;
880 (*out_keysize)++;
881 }
882
883 return master_key;
884}
885
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800886/* Convert a binary key of specified length into an ascii hex string equivalent,
887 * without the leading 0x and with null termination
888 */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800889static void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800890 char *master_key_ascii)
891{
892 unsigned int i, a;
893 unsigned char nibble;
894
895 for (i=0, a=0; i<keysize; i++, a+=2) {
896 /* For each byte, write out two ascii hex digits */
897 nibble = (master_key[i] >> 4) & 0xf;
898 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
899
900 nibble = master_key[i] & 0xf;
901 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
902 }
903
904 /* Add the null termination */
905 master_key_ascii[a] = '\0';
906
907}
908
Ken Sumralldb5e0262013-02-05 17:39:48 -0800909static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
910 char *real_blk_name, const char *name, int fd,
911 char *extra_params)
912{
913 char buffer[DM_CRYPT_BUF_SIZE];
914 struct dm_ioctl *io;
915 struct dm_target_spec *tgt;
916 char *crypt_params;
917 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
918 int i;
919
920 io = (struct dm_ioctl *) buffer;
921
922 /* Load the mapping table for this device */
923 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
924
925 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
926 io->target_count = 1;
927 tgt->status = 0;
928 tgt->sector_start = 0;
929 tgt->length = crypt_ftr->fs_size;
930 strcpy(tgt->target_type, "crypt");
931
932 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
933 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
934 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
935 master_key_ascii, real_blk_name, extra_params);
936 crypt_params += strlen(crypt_params) + 1;
937 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
938 tgt->next = crypt_params - buffer;
939
940 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
941 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
942 break;
943 }
944 usleep(500000);
945 }
946
947 if (i == TABLE_LOAD_RETRIES) {
948 /* We failed to load the table, return an error */
949 return -1;
950 } else {
951 return i + 1;
952 }
953}
954
955
956static int get_dm_crypt_version(int fd, const char *name, int *version)
957{
958 char buffer[DM_CRYPT_BUF_SIZE];
959 struct dm_ioctl *io;
960 struct dm_target_versions *v;
961 int i;
962
963 io = (struct dm_ioctl *) buffer;
964
965 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
966
967 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
968 return -1;
969 }
970
971 /* Iterate over the returned versions, looking for name of "crypt".
972 * When found, get and return the version.
973 */
974 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
975 while (v->next) {
976 if (! strcmp(v->name, "crypt")) {
977 /* We found the crypt driver, return the version, and get out */
978 version[0] = v->version[0];
979 version[1] = v->version[1];
980 version[2] = v->version[2];
981 return 0;
982 }
983 v = (struct dm_target_versions *)(((char *)v) + v->next);
984 }
985
986 return -1;
987}
988
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800989static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -0700990 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800991{
992 char buffer[DM_CRYPT_BUF_SIZE];
993 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
994 char *crypt_params;
995 struct dm_ioctl *io;
996 struct dm_target_spec *tgt;
997 unsigned int minor;
998 int fd;
Ken Sumralle919efe2012-09-29 17:07:41 -0700999 int i;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001000 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001001 int version[3];
1002 char *extra_params;
1003 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001004
1005 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1006 SLOGE("Cannot open device-mapper\n");
1007 goto errout;
1008 }
1009
1010 io = (struct dm_ioctl *) buffer;
1011
1012 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1013 if (ioctl(fd, DM_DEV_CREATE, io)) {
1014 SLOGE("Cannot create dm-crypt device\n");
1015 goto errout;
1016 }
1017
1018 /* Get the device status, in particular, the name of it's device file */
1019 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1020 if (ioctl(fd, DM_DEV_STATUS, io)) {
1021 SLOGE("Cannot retrieve dm-crypt device status\n");
1022 goto errout;
1023 }
1024 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1025 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1026
Ken Sumralldb5e0262013-02-05 17:39:48 -08001027 extra_params = "";
1028 if (! get_dm_crypt_version(fd, name, version)) {
1029 /* Support for allow_discards was added in version 1.11.0 */
1030 if ((version[0] >= 2) ||
1031 ((version[0] == 1) && (version[1] >= 11))) {
1032 extra_params = "1 allow_discards";
1033 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1034 }
Ken Sumralle919efe2012-09-29 17:07:41 -07001035 }
1036
Ken Sumralldb5e0262013-02-05 17:39:48 -08001037 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1038 fd, extra_params);
1039 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001040 SLOGE("Cannot load dm-crypt mapping table.\n");
1041 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001042 } else if (load_count > 1) {
1043 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001044 }
1045
1046 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -08001047 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001048
1049 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1050 SLOGE("Cannot resume the dm-crypt device\n");
1051 goto errout;
1052 }
1053
1054 /* We made it here with no errors. Woot! */
1055 retval = 0;
1056
1057errout:
1058 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1059
1060 return retval;
1061}
1062
Ken Sumrall29d8da82011-05-18 17:20:07 -07001063static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001064{
1065 int fd;
1066 char buffer[DM_CRYPT_BUF_SIZE];
1067 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001068 int retval = -1;
1069
1070 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1071 SLOGE("Cannot open device-mapper\n");
1072 goto errout;
1073 }
1074
1075 io = (struct dm_ioctl *) buffer;
1076
1077 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1078 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1079 SLOGE("Cannot remove dm-crypt device\n");
1080 goto errout;
1081 }
1082
1083 /* We made it here with no errors. Woot! */
1084 retval = 0;
1085
1086errout:
1087 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1088
1089 return retval;
1090
1091}
1092
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001093static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001094 unsigned char *ikey, void *params UNUSED)
1095{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001096 SLOGI("Using pbkdf2 for cryptfs KDF");
1097
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001098 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001099 unsigned int keysize;
1100 char* master_key = (char*)convert_hex_ascii_to_key(passwd, &keysize);
1101 if (!master_key) return -1;
1102 PKCS5_PBKDF2_HMAC_SHA1(master_key, keysize, salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001103 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001104
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001105 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001106 free (master_key);
1107 return 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001108}
1109
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001110static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001111 unsigned char *ikey, void *params)
1112{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001113 SLOGI("Using scrypt for cryptfs KDF");
1114
Kenny Rootc4c70f12013-06-14 12:11:38 -07001115 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1116
1117 int N = 1 << ftr->N_factor;
1118 int r = 1 << ftr->r_factor;
1119 int p = 1 << ftr->p_factor;
1120
1121 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001122 unsigned int keysize;
1123 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &keysize);
1124 if (!master_key) return -1;
1125 crypto_scrypt(master_key, keysize, salt, SALT_LEN, N, r, p, ikey,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001126 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001127
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001128 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001129 free (master_key);
1130 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001131}
1132
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001133static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1134 unsigned char *ikey, void *params)
1135{
1136 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1137
1138 int rc;
1139 unsigned int key_size;
1140 size_t signature_size;
1141 unsigned char* signature;
1142 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1143
1144 int N = 1 << ftr->N_factor;
1145 int r = 1 << ftr->r_factor;
1146 int p = 1 << ftr->p_factor;
1147
1148 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &key_size);
1149 if (!master_key) {
1150 SLOGE("Failed to convert passwd from hex");
1151 return -1;
1152 }
1153
1154 rc = crypto_scrypt(master_key, key_size, salt, SALT_LEN,
1155 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1156 memset(master_key, 0, key_size);
1157 free(master_key);
1158
1159 if (rc) {
1160 SLOGE("scrypt failed");
1161 return -1;
1162 }
1163
1164 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1165 &signature, &signature_size)) {
1166 SLOGE("Signing failed");
1167 return -1;
1168 }
1169
1170 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1171 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1172 free(signature);
1173
1174 if (rc) {
1175 SLOGE("scrypt failed");
1176 return -1;
1177 }
1178
1179 return 0;
1180}
1181
1182static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1183 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001184 unsigned char *encrypted_master_key,
1185 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001186{
1187 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1188 EVP_CIPHER_CTX e_ctx;
1189 int encrypted_len, final_len;
1190
1191 /* Turn the password into a key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001192 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001193
1194 switch (crypt_ftr->kdf_type) {
1195 case KDF_SCRYPT_KEYMASTER:
1196 if (keymaster_create_key(crypt_ftr)) {
1197 SLOGE("keymaster_create_key failed");
1198 return -1;
1199 }
1200
1201 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1202 SLOGE("scrypt failed");
1203 return -1;
1204 }
1205 break;
1206
1207 case KDF_SCRYPT:
1208 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1209 SLOGE("scrypt failed");
1210 return -1;
1211 }
1212 break;
1213
1214 default:
1215 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001216 return -1;
1217 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001218
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001219 /* Initialize the decryption engine */
1220 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1221 SLOGE("EVP_EncryptInit failed\n");
1222 return -1;
1223 }
1224 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001225
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001226 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001227 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
1228 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001229 SLOGE("EVP_EncryptUpdate failed\n");
1230 return -1;
1231 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001232 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001233 SLOGE("EVP_EncryptFinal failed\n");
1234 return -1;
1235 }
1236
1237 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1238 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1239 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001240 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001241
1242 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001243}
1244
JP Abgrall7bdfa522013-11-15 13:42:56 -08001245static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
Ken Sumralle8744072011-01-18 22:01:55 -08001246 unsigned char *encrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001247 unsigned char *decrypted_master_key,
1248 kdf_func kdf, void *kdf_params)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001249{
1250 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 -08001251 EVP_CIPHER_CTX d_ctx;
1252 int decrypted_len, final_len;
1253
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001254 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001255 if (kdf(passwd, salt, ikey, kdf_params)) {
1256 SLOGE("kdf failed");
1257 return -1;
1258 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001259
1260 /* Initialize the decryption engine */
1261 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1262 return -1;
1263 }
1264 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1265 /* Decrypt the master key */
1266 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1267 encrypted_master_key, KEY_LEN_BYTES)) {
1268 return -1;
1269 }
1270 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1271 return -1;
1272 }
1273
1274 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1275 return -1;
1276 } else {
1277 return 0;
1278 }
1279}
1280
Kenny Rootc4c70f12013-06-14 12:11:38 -07001281static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001282{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001283 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1284 *kdf = scrypt_keymaster;
1285 *kdf_params = ftr;
1286 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001287 *kdf = scrypt;
1288 *kdf_params = ftr;
1289 } else {
1290 *kdf = pbkdf2;
1291 *kdf_params = NULL;
1292 }
1293}
1294
JP Abgrall7bdfa522013-11-15 13:42:56 -08001295static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001296 struct crypt_mnt_ftr *crypt_ftr)
1297{
1298 kdf_func kdf;
1299 void *kdf_params;
1300 int ret;
1301
1302 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001303 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, decrypted_master_key, kdf,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001304 kdf_params);
1305 if (ret != 0) {
1306 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001307 }
1308
1309 return ret;
1310}
1311
1312static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1313 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001314 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001315 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001316 EVP_CIPHER_CTX e_ctx;
1317 int encrypted_len, final_len;
1318
1319 /* Get some random bits for a key */
1320 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001321 read(fd, key_buf, sizeof(key_buf));
1322 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001323 close(fd);
1324
1325 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001326 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001327}
1328
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001329static int wait_and_unmount(char *mountpoint)
1330{
1331 int i, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001332#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001333
1334 /* Now umount the tmpfs filesystem */
1335 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
1336 if (umount(mountpoint)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001337 if (errno == EINVAL) {
1338 /* EINVAL is returned if the directory is not a mountpoint,
1339 * i.e. there is no filesystem mounted there. So just get out.
1340 */
1341 break;
1342 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001343 sleep(1);
1344 i++;
1345 } else {
1346 break;
1347 }
1348 }
1349
1350 if (i < WAIT_UNMOUNT_COUNT) {
1351 SLOGD("unmounting %s succeeded\n", mountpoint);
1352 rc = 0;
1353 } else {
1354 SLOGE("unmounting %s failed\n", mountpoint);
1355 rc = -1;
1356 }
1357
1358 return rc;
1359}
1360
Ken Sumrallc5872692013-05-14 15:26:31 -07001361#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001362static int prep_data_fs(void)
1363{
1364 int i;
1365
1366 /* Do the prep of the /data filesystem */
1367 property_set("vold.post_fs_data_done", "0");
1368 property_set("vold.decrypt", "trigger_post_fs_data");
1369 SLOGD("Just triggered post_fs_data\n");
1370
Ken Sumrallc5872692013-05-14 15:26:31 -07001371 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001372 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001373 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001374
1375 property_get("vold.post_fs_data_done", p, "0");
1376 if (*p == '1') {
1377 break;
1378 } else {
1379 usleep(250000);
1380 }
1381 }
1382 if (i == DATA_PREP_TIMEOUT) {
1383 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001384 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001385 return -1;
1386 } else {
1387 SLOGD("post_fs_data done\n");
1388 return 0;
1389 }
1390}
1391
Paul Lawrencef4faa572014-01-29 13:31:03 -08001392static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001393{
1394 char fs_type[32];
1395 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001396 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001397 char fs_options[256];
1398 unsigned long mnt_flags;
1399 struct stat statbuf;
1400 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001401 static int restart_successful = 0;
1402
1403 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001404 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001405 SLOGE("Encrypted filesystem not validated, aborting");
1406 return -1;
1407 }
1408
1409 if (restart_successful) {
1410 SLOGE("System already restarted with encrypted disk, aborting");
1411 return -1;
1412 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001413
Paul Lawrencef4faa572014-01-29 13:31:03 -08001414 if (restart_main) {
1415 /* Here is where we shut down the framework. The init scripts
1416 * start all services in one of three classes: core, main or late_start.
1417 * On boot, we start core and main. Now, we stop main, but not core,
1418 * as core includes vold and a few other really important things that
1419 * we need to keep running. Once main has stopped, we should be able
1420 * to umount the tmpfs /data, then mount the encrypted /data.
1421 * We then restart the class main, and also the class late_start.
1422 * At the moment, I've only put a few things in late_start that I know
1423 * are not needed to bring up the framework, and that also cause problems
1424 * with unmounting the tmpfs /data, but I hope to add add more services
1425 * to the late_start class as we optimize this to decrease the delay
1426 * till the user is asked for the password to the filesystem.
1427 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001428
Paul Lawrencef4faa572014-01-29 13:31:03 -08001429 /* The init files are setup to stop the class main when vold.decrypt is
1430 * set to trigger_reset_main.
1431 */
1432 property_set("vold.decrypt", "trigger_reset_main");
1433 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001434
Paul Lawrencef4faa572014-01-29 13:31:03 -08001435 /* Ugh, shutting down the framework is not synchronous, so until it
1436 * can be fixed, this horrible hack will wait a moment for it all to
1437 * shut down before proceeding. Without it, some devices cannot
1438 * restart the graphics services.
1439 */
1440 sleep(2);
1441 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001442
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001443 /* Now that the framework is shutdown, we should be able to umount()
1444 * the tmpfs filesystem, and mount the real one.
1445 */
1446
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001447 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1448 if (strlen(crypto_blkdev) == 0) {
1449 SLOGE("fs_crypto_blkdev not set\n");
1450 return -1;
1451 }
1452
Ken Sumralle5032c42012-04-01 23:58:44 -07001453 if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001454 /* If ro.crypto.readonly is set to 1, mount the decrypted
1455 * filesystem readonly. This is used when /data is mounted by
1456 * recovery mode.
1457 */
1458 char ro_prop[PROPERTY_VALUE_MAX];
1459 property_get("ro.crypto.readonly", ro_prop, "");
1460 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1461 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1462 rec->flags |= MS_RDONLY;
1463 }
1464
Ken Sumralle5032c42012-04-01 23:58:44 -07001465 /* If that succeeded, then mount the decrypted filesystem */
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001466 fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001467
Ken Sumralle5032c42012-04-01 23:58:44 -07001468 property_set("vold.decrypt", "trigger_load_persist_props");
1469 /* Create necessary paths on /data */
1470 if (prep_data_fs()) {
1471 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001472 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001473
1474 /* startup service classes main and late_start */
1475 property_set("vold.decrypt", "trigger_restart_framework");
1476 SLOGD("Just triggered restart_framework\n");
1477
1478 /* Give it a few moments to get started */
1479 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001480 }
1481
Ken Sumrall0cc16632011-01-18 20:32:26 -08001482 if (rc == 0) {
1483 restart_successful = 1;
1484 }
1485
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001486 return rc;
1487}
1488
Paul Lawrencef4faa572014-01-29 13:31:03 -08001489int cryptfs_restart(void)
1490{
1491 /* Call internal implementation forcing a restart of main service group */
1492 return cryptfs_restart_internal(1);
1493}
1494
Mark Salyzyn3e971272014-01-21 13:27:04 -08001495static int do_crypto_complete(char *mount_point UNUSED)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001496{
1497 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001498 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001499 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001500
1501 property_get("ro.crypto.state", encrypted_state, "");
1502 if (strcmp(encrypted_state, "encrypted") ) {
1503 SLOGE("not running with encryption, aborting");
1504 return 1;
1505 }
1506
Ken Sumrall160b4d62013-04-22 12:15:39 -07001507 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001508 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001509
Ken Sumralle1a45852011-12-14 21:24:27 -08001510 /*
1511 * Only report this error if key_loc is a file and it exists.
1512 * If the device was never encrypted, and /data is not mountable for
1513 * some reason, returning 1 should prevent the UI from presenting the
1514 * a "enter password" screen, or worse, a "press button to wipe the
1515 * device" screen.
1516 */
1517 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1518 SLOGE("master key file does not exist, aborting");
1519 return 1;
1520 } else {
1521 SLOGE("Error getting crypt footer and key\n");
1522 return -1;
1523 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001524 }
1525
1526 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1527 SLOGE("Encryption process didn't finish successfully\n");
1528 return -2; /* -2 is the clue to the UI that there is no usable data on the disk,
1529 * and give the user an option to wipe the disk */
1530 }
1531
1532 /* We passed the test! We shall diminish, and return to the west */
1533 return 0;
1534}
1535
Paul Lawrencef4faa572014-01-29 13:31:03 -08001536static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1537 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001538{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001539 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001540 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001541 char crypto_blkdev[MAXPATHLEN];
1542 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001543 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001544 unsigned int orig_failed_decrypt_count;
1545 int rc;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001546 kdf_func kdf;
1547 void *kdf_params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001548 int use_keymaster = 0;
1549 int upgrade = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001550
Paul Lawrencef4faa572014-01-29 13:31:03 -08001551 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1552 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001553
Paul Lawrencef4faa572014-01-29 13:31:03 -08001554 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
1555 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001556 SLOGE("Failed to decrypt master key\n");
1557 return -1;
1558 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001559 }
1560
Paul Lawrencef4faa572014-01-29 13:31:03 -08001561 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1562
1563 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1564 real_blkdev, crypto_blkdev, label)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001565 SLOGE("Error creating decrypted block device\n");
1566 return -1;
1567 }
1568
Alex Klyubin707795a2013-05-10 15:17:07 -07001569 /* If init detects an encrypted filesystem, it writes a file for each such
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001570 * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
1571 * files and passes that data to me */
1572 /* Create a tmp mount point to try mounting the decryptd fs
1573 * Since we're here, the mount_point should be a tmpfs filesystem, so make
1574 * a directory in it to test mount the decrypted filesystem.
1575 */
1576 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1577 mkdir(tmp_mount_point, 0755);
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001578 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001579 SLOGE("Error temp mounting decrypted block device\n");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001580 delete_crypto_blk_dev(label);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001581 crypt_ftr->failed_decrypt_count++;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001582 } else {
1583 /* Success, so just umount and we'll mount it properly when we restart
1584 * the framework.
1585 */
1586 umount(tmp_mount_point);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001587 crypt_ftr->failed_decrypt_count = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001588 }
1589
Paul Lawrencef4faa572014-01-29 13:31:03 -08001590 if (orig_failed_decrypt_count != crypt_ftr->failed_decrypt_count) {
1591 put_crypt_ftr_and_key(crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001592 }
1593
Paul Lawrencef4faa572014-01-29 13:31:03 -08001594 if (crypt_ftr->failed_decrypt_count) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001595 /* We failed to mount the device, so return an error */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001596 rc = crypt_ftr->failed_decrypt_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001597
1598 } else {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001599 /* Woot! Success! Save the name of the crypto block device
1600 * so we can mount it when restarting the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001601 */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001602 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001603
1604 /* Also save a the master key so we can reencrypted the key
1605 * the key when we want to change the password on it.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001606 */
Jason parks70a4b3f2011-01-28 10:10:47 -06001607 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001608 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001609 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001610 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001611 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001612
JP Abgrall7bdfa522013-11-15 13:42:56 -08001613 /*
1614 * Upgrade if we're not using the latest KDF.
1615 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001616 use_keymaster = keymaster_check_compatibility();
1617 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1618 // Don't allow downgrade to KDF_SCRYPT
1619 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1620 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1621 upgrade = 1;
1622 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001623 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001624 upgrade = 1;
1625 }
1626
1627 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001628 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1629 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001630 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001631 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001632 }
1633 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1634 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001635 }
1636
1637 return rc;
1638}
1639
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001640/* Called by vold when it wants to undo the crypto mapping of a volume it
1641 * manages. This is usually in response to a factory reset, when we want
1642 * to undo the crypto mapping so the volume is formatted in the clear.
1643 */
1644int cryptfs_revert_volume(const char *label)
1645{
1646 return delete_crypto_blk_dev((char *)label);
1647}
1648
Ken Sumrall29d8da82011-05-18 17:20:07 -07001649/*
1650 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1651 * Setup a dm-crypt mapping, use the saved master key from
1652 * setting up the /data mapping, and return the new device path.
1653 */
1654int cryptfs_setup_volume(const char *label, int major, int minor,
1655 char *crypto_sys_path, unsigned int max_path,
1656 int *new_major, int *new_minor)
1657{
1658 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1659 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001660 struct stat statbuf;
1661 int nr_sec, fd;
1662
1663 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1664
Ken Sumrall160b4d62013-04-22 12:15:39 -07001665 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001666
1667 /* Update the fs_size field to be the size of the volume */
1668 fd = open(real_blkdev, O_RDONLY);
1669 nr_sec = get_blkdev_size(fd);
1670 close(fd);
1671 if (nr_sec == 0) {
1672 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1673 return -1;
1674 }
1675
1676 sd_crypt_ftr.fs_size = nr_sec;
1677 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1678 crypto_blkdev, label);
1679
1680 stat(crypto_blkdev, &statbuf);
1681 *new_major = MAJOR(statbuf.st_rdev);
1682 *new_minor = MINOR(statbuf.st_rdev);
1683
1684 /* Create path to sys entry for this block device */
1685 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1686
1687 return 0;
1688}
1689
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001690int cryptfs_crypto_complete(void)
1691{
1692 return do_crypto_complete("/data");
1693}
1694
Paul Lawrencef4faa572014-01-29 13:31:03 -08001695int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1696{
1697 char encrypted_state[PROPERTY_VALUE_MAX];
1698 property_get("ro.crypto.state", encrypted_state, "");
1699 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1700 SLOGE("encrypted fs already validated or not running with encryption,"
1701 " aborting");
1702 return -1;
1703 }
1704
1705 if (get_crypt_ftr_and_key(crypt_ftr)) {
1706 SLOGE("Error getting crypt footer and key");
1707 return -1;
1708 }
1709
1710 return 0;
1711}
1712
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001713int cryptfs_check_passwd(char *passwd)
1714{
Paul Lawrencef4faa572014-01-29 13:31:03 -08001715 struct crypt_mnt_ftr crypt_ftr;
1716 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001717
Paul Lawrencef4faa572014-01-29 13:31:03 -08001718 rc = check_unmounted_and_get_ftr(&crypt_ftr);
1719 if (rc)
1720 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001721
Paul Lawrencef4faa572014-01-29 13:31:03 -08001722 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
1723 DATA_MNT_POINT, "userdata");
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001724
1725 if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001726 cryptfs_clear_password();
1727 password = strdup(passwd);
1728 struct timespec now;
1729 clock_gettime(CLOCK_BOOTTIME, &now);
1730 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001731 }
1732
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001733 return rc;
1734}
1735
Ken Sumrall3ad90722011-10-04 20:38:29 -07001736int cryptfs_verify_passwd(char *passwd)
1737{
1738 struct crypt_mnt_ftr crypt_ftr;
1739 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001740 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001741 char encrypted_state[PROPERTY_VALUE_MAX];
1742 int rc;
1743
1744 property_get("ro.crypto.state", encrypted_state, "");
1745 if (strcmp(encrypted_state, "encrypted") ) {
1746 SLOGE("device not encrypted, aborting");
1747 return -2;
1748 }
1749
1750 if (!master_key_saved) {
1751 SLOGE("encrypted fs not yet mounted, aborting");
1752 return -1;
1753 }
1754
1755 if (!saved_mount_point) {
1756 SLOGE("encrypted fs failed to save mount point, aborting");
1757 return -1;
1758 }
1759
Ken Sumrall160b4d62013-04-22 12:15:39 -07001760 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001761 SLOGE("Error getting crypt footer and key\n");
1762 return -1;
1763 }
1764
1765 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1766 /* If the device has no password, then just say the password is valid */
1767 rc = 0;
1768 } else {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001769 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001770 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1771 /* They match, the password is correct */
1772 rc = 0;
1773 } else {
1774 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1775 sleep(1);
1776 rc = 1;
1777 }
1778 }
1779
1780 return rc;
1781}
1782
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001783/* Initialize a crypt_mnt_ftr structure. The keysize is
1784 * defaulted to 16 bytes, and the filesystem size to 0.
1785 * Presumably, at a minimum, the caller will update the
1786 * filesystem size and crypto_type_name after calling this function.
1787 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001788static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001789{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001790 off64_t off;
1791
1792 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001793 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001794 ftr->major_version = CURRENT_MAJOR_VERSION;
1795 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001796 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001797 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001798
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001799 switch (keymaster_check_compatibility()) {
1800 case 1:
1801 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1802 break;
1803
1804 case 0:
1805 ftr->kdf_type = KDF_SCRYPT;
1806 break;
1807
1808 default:
1809 SLOGE("keymaster_check_compatibility failed");
1810 return -1;
1811 }
1812
Kenny Rootc4c70f12013-06-14 12:11:38 -07001813 get_device_scrypt_params(ftr);
1814
Ken Sumrall160b4d62013-04-22 12:15:39 -07001815 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1816 if (get_crypt_ftr_info(NULL, &off) == 0) {
1817 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1818 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1819 ftr->persist_data_size;
1820 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001821
1822 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001823}
1824
Ken Sumrall29d8da82011-05-18 17:20:07 -07001825static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001826{
Ken Sumralle550f782013-08-20 13:48:23 -07001827 const char *args[10];
1828 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1829 int num_args;
1830 int status;
1831 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001832 int rc = -1;
1833
Ken Sumrall29d8da82011-05-18 17:20:07 -07001834 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001835 args[0] = "/system/bin/make_ext4fs";
1836 args[1] = "-a";
1837 args[2] = "/data";
1838 args[3] = "-l";
1839 snprintf(size_str, sizeof(size_str), "%lld", size * 512);
1840 args[4] = size_str;
1841 args[5] = crypto_blkdev;
1842 num_args = 6;
1843 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1844 args[0], args[1], args[2], args[3], args[4], args[5]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001845 } else if (type== FAT_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001846 args[0] = "/system/bin/newfs_msdos";
1847 args[1] = "-F";
1848 args[2] = "32";
1849 args[3] = "-O";
1850 args[4] = "android";
1851 args[5] = "-c";
1852 args[6] = "8";
1853 args[7] = "-s";
1854 snprintf(size_str, sizeof(size_str), "%lld", size);
1855 args[8] = size_str;
1856 args[9] = crypto_blkdev;
1857 num_args = 10;
1858 SLOGI("Making empty filesystem with command %s %s %s %s %s %s %s %s %s %s\n",
1859 args[0], args[1], args[2], args[3], args[4], args[5],
1860 args[6], args[7], args[8], args[9]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001861 } else {
1862 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1863 return -1;
1864 }
1865
Ken Sumralle550f782013-08-20 13:48:23 -07001866 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1867
1868 if (tmp != 0) {
1869 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001870 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07001871 if (WIFEXITED(status)) {
1872 if (WEXITSTATUS(status)) {
1873 SLOGE("Error creating filesystem on %s, exit status %d ",
1874 crypto_blkdev, WEXITSTATUS(status));
1875 } else {
1876 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
1877 rc = 0;
1878 }
1879 } else {
1880 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
1881 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001882 }
1883
1884 return rc;
1885}
1886
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001887#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08001888#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
1889#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001890
1891/* aligned 32K writes tends to make flash happy.
1892 * SD card association recommends it.
1893 */
1894#define BLOCKS_AT_A_TIME 8
1895
1896struct encryptGroupsData
1897{
1898 int realfd;
1899 int cryptofd;
1900 off64_t numblocks;
1901 off64_t one_pct, cur_pct, new_pct;
1902 off64_t blocks_already_done, tot_numblocks;
1903 char* real_blkdev, * crypto_blkdev;
1904 int count;
1905 off64_t offset;
1906 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08001907 off64_t last_written_sector;
1908 int completed;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001909};
1910
1911static void update_progress(struct encryptGroupsData* data)
1912{
1913 data->blocks_already_done++;
1914 data->new_pct = data->blocks_already_done / data->one_pct;
1915 if (data->new_pct > data->cur_pct) {
1916 char buf[8];
1917 data->cur_pct = data->new_pct;
1918 snprintf(buf, sizeof(buf), "%lld", data->cur_pct);
1919 property_set("vold.encrypt_progress", buf);
1920 }
1921}
1922
1923static int flush_outstanding_data(struct encryptGroupsData* data)
1924{
1925 if (data->count == 0) {
1926 return 0;
1927 }
1928
1929 SLOGV("Copying %d blocks at offset %llx", data->count, data->offset);
1930
1931 if (pread64(data->realfd, data->buffer,
1932 info.block_size * data->count, data->offset)
1933 <= 0) {
1934 SLOGE("Error reading real_blkdev %s for inplace encrypt",
1935 data->real_blkdev);
1936 return -1;
1937 }
1938
1939 if (pwrite64(data->cryptofd, data->buffer,
1940 info.block_size * data->count, data->offset)
1941 <= 0) {
1942 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
1943 data->crypto_blkdev);
1944 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08001945 } else {
1946 SLOGI("Encrypted %d blocks at sector %lld",
1947 data->count, data->offset / info.block_size * CRYPT_SECTOR_SIZE);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001948 }
1949
1950 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08001951 data->last_written_sector = (data->offset + data->count)
1952 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001953 return 0;
1954}
1955
1956static int encrypt_groups(struct encryptGroupsData* data)
1957{
1958 unsigned int i;
1959 u8 *block_bitmap = 0;
1960 unsigned int block;
1961 off64_t ret;
1962 int rc = -1;
1963
1964 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
1965 if (!data->buffer) {
1966 SLOGE("Failed to allocate crypto buffer");
1967 goto errout;
1968 }
1969
1970 block_bitmap = malloc(info.block_size);
1971 if (!block_bitmap) {
1972 SLOGE("failed to allocate block bitmap");
1973 goto errout;
1974 }
1975
1976 for (i = 0; i < aux_info.groups; ++i) {
1977 SLOGI("Encrypting group %d", i);
1978
1979 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
1980 u32 block_count = min(info.blocks_per_group,
1981 aux_info.len_blocks - first_block);
1982
1983 off64_t offset = (u64)info.block_size
1984 * aux_info.bg_desc[i].bg_block_bitmap;
1985
1986 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
1987 if (ret != (int)info.block_size) {
1988 SLOGE("failed to read all of block group bitmap %d", i);
1989 goto errout;
1990 }
1991
1992 offset = (u64)info.block_size * first_block;
1993
1994 data->count = 0;
1995
1996 for (block = 0; block < block_count; block++) {
1997 update_progress(data);
1998 if (bitmap_get_bit(block_bitmap, block)) {
1999 if (data->count == 0) {
2000 data->offset = offset;
2001 }
2002 data->count++;
2003 } else {
2004 if (flush_outstanding_data(data)) {
2005 goto errout;
2006 }
2007 }
2008
2009 offset += info.block_size;
2010
2011 /* Write data if we are aligned or buffer size reached */
2012 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2013 || data->count == BLOCKS_AT_A_TIME) {
2014 if (flush_outstanding_data(data)) {
2015 goto errout;
2016 }
2017 }
Paul Lawrence87999172014-02-20 12:21:31 -08002018
2019 if (!is_battery_ok()) {
2020 SLOGE("Stopping encryption due to low battery");
2021 rc = 0;
2022 goto errout;
2023 }
2024
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002025 }
2026 if (flush_outstanding_data(data)) {
2027 goto errout;
2028 }
2029 }
2030
Paul Lawrence87999172014-02-20 12:21:31 -08002031 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002032 rc = 0;
2033
2034errout:
2035 free(data->buffer);
2036 free(block_bitmap);
2037 return rc;
2038}
2039
2040static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2041 char *real_blkdev,
2042 off64_t size,
2043 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002044 off64_t tot_size,
2045 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002046{
2047 int i;
2048 struct encryptGroupsData data;
2049 int rc = -1;
2050
Paul Lawrence87999172014-02-20 12:21:31 -08002051 if (previously_encrypted_upto > *size_already_done) {
2052 SLOGD("Not fast encrypting since resuming part way through");
2053 return -1;
2054 }
2055
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002056 memset(&data, 0, sizeof(data));
2057 data.real_blkdev = real_blkdev;
2058 data.crypto_blkdev = crypto_blkdev;
2059
2060 if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
2061 SLOGE("Error opening real_blkdev %s for inplace encrypt\n",
2062 real_blkdev);
2063 goto errout;
2064 }
2065
2066 if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
2067 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n",
2068 crypto_blkdev);
2069 goto errout;
2070 }
2071
2072 if (setjmp(setjmp_env)) {
2073 SLOGE("Reading extent caused an exception");
2074 goto errout;
2075 }
2076
2077 if (read_ext(data.realfd, 0) != 0) {
2078 SLOGE("Failed to read extent");
2079 goto errout;
2080 }
2081
2082 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2083 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2084 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2085
2086 SLOGI("Encrypting filesystem in place...");
2087
2088 data.one_pct = data.tot_numblocks / 100;
2089 data.cur_pct = 0;
2090
2091 rc = encrypt_groups(&data);
2092 if (rc) {
2093 SLOGE("Error encrypting groups");
2094 goto errout;
2095 }
2096
Paul Lawrence87999172014-02-20 12:21:31 -08002097 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002098 rc = 0;
2099
2100errout:
2101 close(data.realfd);
2102 close(data.cryptofd);
2103
2104 return rc;
2105}
2106
2107static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2108 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002109 off64_t tot_size,
2110 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002111{
2112 int realfd, cryptofd;
2113 char *buf[CRYPT_INPLACE_BUFSIZE];
2114 int rc = -1;
2115 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002116 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002117 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002118
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002119 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
2120 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
2121 return -1;
2122 }
2123
2124 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
2125 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
2126 close(realfd);
2127 return -1;
2128 }
2129
2130 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2131 * The size passed in is the number of 512 byte sectors in the filesystem.
2132 * So compute the number of whole 4K blocks we should read/write,
2133 * and the remainder.
2134 */
2135 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2136 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002137 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2138 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002139
2140 SLOGE("Encrypting filesystem in place...");
2141
Paul Lawrence87999172014-02-20 12:21:31 -08002142 i = previously_encrypted_upto + 1 - *size_already_done;
2143
2144 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2145 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2146 goto errout;
2147 }
2148
2149 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2150 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2151 goto errout;
2152 }
2153
2154 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2155 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2156 SLOGE("Error reading initial sectors from real_blkdev %s for "
2157 "inplace encrypt\n", crypto_blkdev);
2158 goto errout;
2159 }
2160 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2161 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2162 "inplace encrypt\n", crypto_blkdev);
2163 goto errout;
2164 } else {
2165 SLOGI("Encrypted 1 block at %lld", i);
2166 }
2167 }
2168
Ken Sumrall29d8da82011-05-18 17:20:07 -07002169 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002170 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002171 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002172 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002173 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002174 if (new_pct > cur_pct) {
2175 char buf[8];
2176
2177 cur_pct = new_pct;
2178 snprintf(buf, sizeof(buf), "%lld", cur_pct);
2179 property_set("vold.encrypt_progress", buf);
2180 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002181 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002182 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002183 goto errout;
2184 }
2185 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002186 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2187 goto errout;
2188 } else {
2189 SLOGD("Encrypted %d block at %lld",
2190 CRYPT_SECTORS_PER_BUFSIZE,
2191 i * CRYPT_SECTORS_PER_BUFSIZE);
2192 }
2193
2194 if (!is_battery_ok()) {
2195 SLOGE("Stopping encryption due to low battery");
2196 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2197 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002198 goto errout;
2199 }
2200 }
2201
2202 /* Do any remaining sectors */
2203 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002204 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2205 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002206 goto errout;
2207 }
Paul Lawrence87999172014-02-20 12:21:31 -08002208 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2209 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002210 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002211 } else {
2212 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002213 }
2214 }
2215
Ken Sumrall29d8da82011-05-18 17:20:07 -07002216 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002217 rc = 0;
2218
2219errout:
2220 close(realfd);
2221 close(cryptofd);
2222
2223 return rc;
2224}
2225
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002226static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2227 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002228 off64_t tot_size,
2229 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002230{
Paul Lawrence87999172014-02-20 12:21:31 -08002231 if (previously_encrypted_upto) {
2232 SLOGD("Continuing encryption from %lld", previously_encrypted_upto);
2233 }
2234
2235 if (*size_already_done + size < previously_encrypted_upto) {
2236 *size_already_done += size;
2237 return 0;
2238 }
2239
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002240 if (cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002241 size, size_already_done,
2242 tot_size, previously_encrypted_upto) == 0) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002243 return 0;
2244 }
2245
2246 return cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002247 size, size_already_done, tot_size,
2248 previously_encrypted_upto);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002249}
2250
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002251#define CRYPTO_ENABLE_WIPE 1
2252#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002253
2254#define FRAMEWORK_BOOT_WAIT 60
2255
Ken Sumrall29d8da82011-05-18 17:20:07 -07002256static inline int should_encrypt(struct volume_info *volume)
2257{
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002258 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
Ken Sumrall29d8da82011-05-18 17:20:07 -07002259 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
2260}
2261
Paul Lawrence87999172014-02-20 12:21:31 -08002262static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2263{
2264 int fd = open(filename, O_RDONLY);
2265 if (fd == -1) {
2266 SLOGE("Error opening file %s", filename);
2267 return -1;
2268 }
2269
2270 char block[CRYPT_INPLACE_BUFSIZE];
2271 memset(block, 0, sizeof(block));
2272 if (unix_read(fd, block, sizeof(block)) < 0) {
2273 SLOGE("Error reading file %s", filename);
2274 close(fd);
2275 return -1;
2276 }
2277
2278 close(fd);
2279
2280 SHA256_CTX c;
2281 SHA256_Init(&c);
2282 SHA256_Update(&c, block, sizeof(block));
2283 SHA256_Final(buf, &c);
2284
2285 return 0;
2286}
2287
2288static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2289 char *crypto_blkdev, char *real_blkdev,
2290 int previously_encrypted_upto)
2291{
2292 off64_t cur_encryption_done=0, tot_encryption_size=0;
2293 int i, rc = -1;
2294
2295 if (!is_battery_ok()) {
2296 SLOGE("Stopping encryption due to low battery");
2297 return 0;
2298 }
2299
2300 /* The size of the userdata partition, and add in the vold volumes below */
2301 tot_encryption_size = crypt_ftr->fs_size;
2302
2303 if (how == CRYPTO_ENABLE_WIPE) {
2304 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, EXT4_FS);
2305 } else if (how == CRYPTO_ENABLE_INPLACE) {
2306 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2307 crypt_ftr->fs_size, &cur_encryption_done,
2308 tot_encryption_size,
2309 previously_encrypted_upto);
2310
2311 if (!rc && cur_encryption_done != (off64_t)crypt_ftr->fs_size) {
2312 crypt_ftr->encrypted_upto = cur_encryption_done;
2313 }
2314
2315 if (!rc && !crypt_ftr->encrypted_upto) {
2316 /* The inplace routine never actually sets the progress to 100% due
2317 * to the round down nature of integer division, so set it here */
2318 property_set("vold.encrypt_progress", "100");
2319 }
2320 } else {
2321 /* Shouldn't happen */
2322 SLOGE("cryptfs_enable: internal error, unknown option\n");
2323 rc = -1;
2324 }
2325
2326 return rc;
2327}
2328
Paul Lawrence13486032014-02-03 13:28:11 -08002329int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
2330 int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002331{
2332 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002333 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07002334 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002335 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07002336 int rc=-1, fd, i, ret;
Paul Lawrence87999172014-02-20 12:21:31 -08002337 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002338 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002339 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002340 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002341 char key_loc[PROPERTY_VALUE_MAX];
2342 char fuse_sdcard[PROPERTY_VALUE_MAX];
2343 char *sd_mnt_point;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002344 int num_vols;
2345 struct volume_info *vol_list = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002346 off64_t previously_encrypted_upto = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002347
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002348 if (!strcmp(howarg, "wipe")) {
2349 how = CRYPTO_ENABLE_WIPE;
2350 } else if (! strcmp(howarg, "inplace")) {
2351 how = CRYPTO_ENABLE_INPLACE;
2352 } else {
2353 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002354 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002355 }
2356
Paul Lawrence87999172014-02-20 12:21:31 -08002357 /* See if an encryption was underway and interrupted */
2358 if (how == CRYPTO_ENABLE_INPLACE
2359 && get_crypt_ftr_and_key(&crypt_ftr) == 0
2360 && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
2361 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2362 crypt_ftr.encrypted_upto = 0;
2363 }
2364
2365 property_get("ro.crypto.state", encrypted_state, "");
2366 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2367 SLOGE("Device is already running encrypted, aborting");
2368 goto error_unencrypted;
2369 }
2370
2371 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2372 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002373 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002374
Ken Sumrall3ed82362011-01-28 23:31:16 -08002375 /* Get the size of the real block device */
2376 fd = open(real_blkdev, O_RDONLY);
2377 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
2378 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2379 goto error_unencrypted;
2380 }
2381 close(fd);
2382
2383 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002384 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002385 unsigned int fs_size_sec, max_fs_size_sec;
2386
2387 fs_size_sec = get_fs_size(real_blkdev);
Paul Lawrence87999172014-02-20 12:21:31 -08002388 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002389
2390 if (fs_size_sec > max_fs_size_sec) {
2391 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2392 goto error_unencrypted;
2393 }
2394 }
2395
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002396 /* Get a wakelock as this may take a while, and we don't want the
2397 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2398 * wants to keep the screen on, it can grab a full wakelock.
2399 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002400 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002401 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2402
Jeff Sharkey7382f812012-08-23 14:08:59 -07002403 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07002404 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07002405 if (!sd_mnt_point) {
2406 sd_mnt_point = getenv("EXTERNAL_STORAGE");
2407 }
2408 if (!sd_mnt_point) {
2409 sd_mnt_point = "/mnt/sdcard";
2410 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07002411
Paul Lawrence87999172014-02-20 12:21:31 -08002412 /* TODO
2413 * Currently do not have test devices with multiple encryptable volumes.
2414 * When we acquire some, re-add support.
2415 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002416 num_vols=vold_getNumDirectVolumes();
2417 vol_list = malloc(sizeof(struct volume_info) * num_vols);
2418 vold_getDirectVolumeList(vol_list);
2419
2420 for (i=0; i<num_vols; i++) {
2421 if (should_encrypt(&vol_list[i])) {
Paul Lawrence87999172014-02-20 12:21:31 -08002422 SLOGE("Cannot encrypt if there are multiple encryptable volumes"
2423 "%s\n", vol_list[i].label);
2424 goto error_unencrypted;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002425 }
2426 }
2427
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002428 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002429 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002430 */
2431 property_set("vold.decrypt", "trigger_shutdown_framework");
2432 SLOGD("Just asked init to shut down class main\n");
2433
Ken Sumrall425524d2012-06-14 20:55:28 -07002434 if (vold_unmountAllAsecs()) {
2435 /* Just report the error. If any are left mounted,
2436 * umounting /data below will fail and handle the error.
2437 */
2438 SLOGE("Error unmounting internal asecs");
2439 }
2440
Ken Sumrall29d8da82011-05-18 17:20:07 -07002441 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
2442 if (!strcmp(fuse_sdcard, "true")) {
2443 /* This is a device using the fuse layer to emulate the sdcard semantics
2444 * on top of the userdata partition. vold does not manage it, it is managed
2445 * by the sdcard service. The sdcard service was killed by the property trigger
2446 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
2447 * unlike the case for vold managed devices above.
2448 */
2449 if (wait_and_unmount(sd_mnt_point)) {
2450 goto error_shutting_down;
2451 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002452 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002453
2454 /* Now unmount the /data partition. */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002455 if (wait_and_unmount(DATA_MNT_POINT)) {
JP Abgrall502dc742013-11-01 13:06:20 -07002456 if (allow_reboot) {
2457 goto error_shutting_down;
2458 } else {
2459 goto error_unencrypted;
2460 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002461 }
2462
2463 /* Do extra work for a better UX when doing the long inplace encryption */
2464 if (how == CRYPTO_ENABLE_INPLACE) {
2465 /* Now that /data is unmounted, we need to mount a tmpfs
2466 * /data, set a property saying we're doing inplace encryption,
2467 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002468 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002469 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002470 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002471 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002472 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002473 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002474
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002475 /* restart the framework. */
2476 /* Create necessary paths on /data */
2477 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002478 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002479 }
2480
Ken Sumrall92736ef2012-10-17 20:57:14 -07002481 /* Ugh, shutting down the framework is not synchronous, so until it
2482 * can be fixed, this horrible hack will wait a moment for it all to
2483 * shut down before proceeding. Without it, some devices cannot
2484 * restart the graphics services.
2485 */
2486 sleep(2);
2487
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002488 /* startup service classes main and late_start */
2489 property_set("vold.decrypt", "trigger_restart_min_framework");
2490 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002491
Ken Sumrall7df84122011-01-18 14:04:08 -08002492 /* OK, the framework is restarted and will soon be showing a
2493 * progress bar. Time to setup an encrypted mapping, and
2494 * either write a new filesystem, or encrypt in place updating
2495 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002496 */
2497 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002498
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002499 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002500 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence87999172014-02-20 12:21:31 -08002501 if (previously_encrypted_upto == 0) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002502 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2503 goto error_shutting_down;
2504 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002505
Paul Lawrence87999172014-02-20 12:21:31 -08002506 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2507 crypt_ftr.fs_size = nr_sec
2508 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2509 } else {
2510 crypt_ftr.fs_size = nr_sec;
2511 }
2512 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
2513 crypt_ftr.crypt_type = crypt_type;
2514 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002515
Paul Lawrence87999172014-02-20 12:21:31 -08002516 /* Make an encrypted master key */
2517 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
2518 SLOGE("Cannot create encrypted master key\n");
2519 goto error_shutting_down;
2520 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002521
Paul Lawrence87999172014-02-20 12:21:31 -08002522 /* Write the key to the end of the partition */
2523 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002524
Paul Lawrence87999172014-02-20 12:21:31 -08002525 /* If any persistent data has been remembered, save it.
2526 * If none, create a valid empty table and save that.
2527 */
2528 if (!persist_data) {
2529 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
2530 if (pdata) {
2531 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2532 persist_data = pdata;
2533 }
2534 }
2535 if (persist_data) {
2536 save_persistent_data();
2537 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002538 }
2539
JP Abgrall7bdfa522013-11-15 13:42:56 -08002540 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002541 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
2542 "userdata");
2543
Paul Lawrence87999172014-02-20 12:21:31 -08002544 /* If we are continuing, check checksums match */
2545 rc = 0;
2546 if (previously_encrypted_upto) {
2547 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2548 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002549
Paul Lawrence87999172014-02-20 12:21:31 -08002550 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2551 sizeof(hash_first_block)) != 0) {
2552 SLOGE("Checksums do not match - trigger wipe");
2553 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002554 }
2555 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002556
Paul Lawrence87999172014-02-20 12:21:31 -08002557 if (!rc) {
2558 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
2559 crypto_blkdev, real_blkdev,
2560 previously_encrypted_upto);
2561 }
2562
2563 /* Calculate checksum if we are not finished */
2564 if (!rc && crypt_ftr.encrypted_upto) {
2565 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2566 crypt_ftr.hash_first_block);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002567 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002568 SLOGE("Error calculating checksum for continuing encryption");
2569 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002570 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002571 }
2572
2573 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002574 delete_crypto_blk_dev("userdata");
Ken Sumrall29d8da82011-05-18 17:20:07 -07002575
2576 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002577
2578 if (! rc) {
2579 /* Success */
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002580
Ken Sumralld33d4172011-02-01 00:49:13 -08002581 /* Clear the encryption in progres flag in the footer */
Paul Lawrence87999172014-02-20 12:21:31 -08002582 if (!crypt_ftr.encrypted_upto) {
2583 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
2584 } else {
2585 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2586 crypt_ftr.encrypted_upto);
2587 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002588 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002589
Ken Sumrall29d8da82011-05-18 17:20:07 -07002590 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08002591 /* Partially encrypted - ensure writes are flushed to ssd */
2592
2593 if (!crypt_ftr.encrypted_upto) {
2594 cryptfs_reboot(reboot);
2595 } else {
2596 cryptfs_reboot(shutdown);
2597 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002598 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002599 char value[PROPERTY_VALUE_MAX];
2600
Ken Sumrall319369a2012-06-27 16:30:18 -07002601 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002602 if (!strcmp(value, "1")) {
2603 /* wipe data if encryption failed */
2604 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
2605 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07002606 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002607 if (fd >= 0) {
2608 write(fd, "--wipe_data", strlen("--wipe_data") + 1);
2609 close(fd);
2610 } else {
2611 SLOGE("could not open /cache/recovery/command\n");
2612 }
Paul Lawrence87999172014-02-20 12:21:31 -08002613 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002614 } else {
2615 /* set property to trigger dialog */
2616 property_set("vold.encrypt_progress", "error_partially_encrypted");
2617 release_wake_lock(lockid);
2618 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002619 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002620 }
2621
Ken Sumrall3ed82362011-01-28 23:31:16 -08002622 /* hrm, the encrypt step claims success, but the reboot failed.
2623 * This should not happen.
2624 * Set the property and return. Hope the framework can deal with it.
2625 */
2626 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002627 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002628 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002629
2630error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07002631 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002632 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002633 if (lockid[0]) {
2634 release_wake_lock(lockid);
2635 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002636 return -1;
2637
2638error_shutting_down:
2639 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2640 * but the framework is stopped and not restarted to show the error, so it's up to
2641 * vold to restart the system.
2642 */
2643 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08002644 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002645
2646 /* shouldn't get here */
2647 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07002648 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002649 if (lockid[0]) {
2650 release_wake_lock(lockid);
2651 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002652 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002653}
2654
Paul Lawrence45f10532014-04-04 18:11:56 +00002655int cryptfs_enable(char *howarg, int type, char *passwd, int allow_reboot)
Paul Lawrence13486032014-02-03 13:28:11 -08002656{
Paul Lawrence45f10532014-04-04 18:11:56 +00002657 return cryptfs_enable_internal(howarg, type, passwd, allow_reboot);
Paul Lawrence13486032014-02-03 13:28:11 -08002658}
2659
2660int cryptfs_enable_default(char *howarg, int allow_reboot)
2661{
2662 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
2663 DEFAULT_PASSWORD, allow_reboot);
2664}
2665
2666int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002667{
2668 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002669 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002670
2671 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002672 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002673 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002674 return -1;
2675 }
2676
Paul Lawrencef4faa572014-01-29 13:31:03 -08002677 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2678 SLOGE("Invalid crypt_type %d", crypt_type);
2679 return -1;
2680 }
2681
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002682 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002683 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002684 SLOGE("Error getting crypt footer and key");
2685 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002686 }
2687
Paul Lawrencef4faa572014-01-29 13:31:03 -08002688 crypt_ftr.crypt_type = crypt_type;
2689
2690 encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
2691 : newpw,
2692 crypt_ftr.salt,
2693 saved_master_key,
2694 crypt_ftr.master_key,
2695 &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002696
Jason parks70a4b3f2011-01-28 10:10:47 -06002697 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002698 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002699
2700 return 0;
2701}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002702
2703static int persist_get_key(char *fieldname, char *value)
2704{
2705 unsigned int i;
2706
2707 if (persist_data == NULL) {
2708 return -1;
2709 }
2710 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2711 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2712 /* We found it! */
2713 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2714 return 0;
2715 }
2716 }
2717
2718 return -1;
2719}
2720
2721static int persist_set_key(char *fieldname, char *value, int encrypted)
2722{
2723 unsigned int i;
2724 unsigned int num;
2725 struct crypt_mnt_ftr crypt_ftr;
2726 unsigned int max_persistent_entries;
2727 unsigned int dsize;
2728
2729 if (persist_data == NULL) {
2730 return -1;
2731 }
2732
2733 /* If encrypted, use the values from the crypt_ftr, otherwise
2734 * use the values for the current spec.
2735 */
2736 if (encrypted) {
2737 if(get_crypt_ftr_and_key(&crypt_ftr)) {
2738 return -1;
2739 }
2740 dsize = crypt_ftr.persist_data_size;
2741 } else {
2742 dsize = CRYPT_PERSIST_DATA_SIZE;
2743 }
2744 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2745 sizeof(struct crypt_persist_entry);
2746
2747 num = persist_data->persist_valid_entries;
2748
2749 for (i = 0; i < num; i++) {
2750 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2751 /* We found an existing entry, update it! */
2752 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2753 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2754 return 0;
2755 }
2756 }
2757
2758 /* We didn't find it, add it to the end, if there is room */
2759 if (persist_data->persist_valid_entries < max_persistent_entries) {
2760 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2761 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2762 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2763 persist_data->persist_valid_entries++;
2764 return 0;
2765 }
2766
2767 return -1;
2768}
2769
2770/* Return the value of the specified field. */
2771int cryptfs_getfield(char *fieldname, char *value, int len)
2772{
2773 char temp_value[PROPERTY_VALUE_MAX];
2774 char real_blkdev[MAXPATHLEN];
2775 /* 0 is success, 1 is not encrypted,
2776 * -1 is value not set, -2 is any other error
2777 */
2778 int rc = -2;
2779
2780 if (persist_data == NULL) {
2781 load_persistent_data();
2782 if (persist_data == NULL) {
2783 SLOGE("Getfield error, cannot load persistent data");
2784 goto out;
2785 }
2786 }
2787
2788 if (!persist_get_key(fieldname, temp_value)) {
2789 /* We found it, copy it to the caller's buffer and return */
2790 strlcpy(value, temp_value, len);
2791 rc = 0;
2792 } else {
2793 /* Sadness, it's not there. Return the error */
2794 rc = -1;
2795 }
2796
2797out:
2798 return rc;
2799}
2800
2801/* Set the value of the specified field. */
2802int cryptfs_setfield(char *fieldname, char *value)
2803{
2804 struct crypt_persist_data stored_pdata;
2805 struct crypt_persist_data *pdata_p;
2806 struct crypt_mnt_ftr crypt_ftr;
2807 char encrypted_state[PROPERTY_VALUE_MAX];
2808 /* 0 is success, -1 is an error */
2809 int rc = -1;
2810 int encrypted = 0;
2811
2812 if (persist_data == NULL) {
2813 load_persistent_data();
2814 if (persist_data == NULL) {
2815 SLOGE("Setfield error, cannot load persistent data");
2816 goto out;
2817 }
2818 }
2819
2820 property_get("ro.crypto.state", encrypted_state, "");
2821 if (!strcmp(encrypted_state, "encrypted") ) {
2822 encrypted = 1;
2823 }
2824
2825 if (persist_set_key(fieldname, value, encrypted)) {
2826 goto out;
2827 }
2828
2829 /* If we are running encrypted, save the persistent data now */
2830 if (encrypted) {
2831 if (save_persistent_data()) {
2832 SLOGE("Setfield error, cannot save persistent data");
2833 goto out;
2834 }
2835 }
2836
2837 rc = 0;
2838
2839out:
2840 return rc;
2841}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002842
2843/* Checks userdata. Attempt to mount the volume if default-
2844 * encrypted.
2845 * On success trigger next init phase and return 0.
2846 * Currently do not handle failure - see TODO below.
2847 */
2848int cryptfs_mount_default_encrypted(void)
2849{
2850 char decrypt_state[PROPERTY_VALUE_MAX];
2851 property_get("vold.decrypt", decrypt_state, "0");
2852 if (!strcmp(decrypt_state, "0")) {
2853 SLOGE("Not encrypted - should not call here");
2854 } else {
2855 int crypt_type = cryptfs_get_password_type();
2856 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2857 SLOGE("Bad crypt type - error");
2858 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2859 SLOGD("Password is not default - "
2860 "starting min framework to prompt");
2861 property_set("vold.decrypt", "trigger_restart_min_framework");
2862 return 0;
2863 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2864 SLOGD("Password is default - restarting filesystem");
2865 cryptfs_restart_internal(0);
2866 return 0;
2867 } else {
2868 SLOGE("Encrypted, default crypt type but can't decrypt");
2869 }
2870 }
2871
2872 /** @TODO make sure we factory wipe in this situation
2873 * In general if we got here there is no recovery
2874 */
2875 return 0;
2876}
2877
2878/* Returns type of the password, default, pattern, pin or password.
2879 */
2880int cryptfs_get_password_type(void)
2881{
2882 struct crypt_mnt_ftr crypt_ftr;
2883
2884 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2885 SLOGE("Error getting crypt footer and key\n");
2886 return -1;
2887 }
2888
2889 return crypt_ftr.crypt_type;
2890}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002891
Paul Lawrence399317e2014-03-10 13:20:50 -07002892char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002893{
Paul Lawrence399317e2014-03-10 13:20:50 -07002894 struct timespec now;
2895 clock_gettime(CLOCK_MONOTONIC, &now);
2896 if (now.tv_sec < password_expiry_time) {
2897 return password;
2898 } else {
2899 cryptfs_clear_password();
2900 return 0;
2901 }
2902}
2903
2904void cryptfs_clear_password()
2905{
2906 if (password) {
2907 size_t len = strlen(password);
2908 memset(password, 0, len);
2909 free(password);
2910 password = 0;
2911 password_expiry_time = 0;
2912 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002913}