blob: bd03c08d8d00b463044372949864dcd4d55b7f9d [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;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07001903 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001904 char* real_blkdev, * crypto_blkdev;
1905 int count;
1906 off64_t offset;
1907 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08001908 off64_t last_written_sector;
1909 int completed;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001910};
1911
Paul Lawrence58c58cf2014-06-04 13:12:21 -07001912static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001913{
1914 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07001915
1916 if (is_used) {
1917 data->used_blocks_already_done++;
1918 }
1919
1920 if (data->tot_used_blocks) {
1921 data->new_pct = data->used_blocks_already_done / data->one_pct;
1922 } else {
1923 data->new_pct = data->blocks_already_done / data->one_pct;
1924 }
1925
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001926 if (data->new_pct > data->cur_pct) {
1927 char buf[8];
1928 data->cur_pct = data->new_pct;
1929 snprintf(buf, sizeof(buf), "%lld", data->cur_pct);
1930 property_set("vold.encrypt_progress", buf);
Paul Lawrence58c58cf2014-06-04 13:12:21 -07001931
1932 SLOGI("Encrypted %lld percent of drive", data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001933 }
1934}
1935
1936static int flush_outstanding_data(struct encryptGroupsData* data)
1937{
1938 if (data->count == 0) {
1939 return 0;
1940 }
1941
1942 SLOGV("Copying %d blocks at offset %llx", data->count, data->offset);
1943
1944 if (pread64(data->realfd, data->buffer,
1945 info.block_size * data->count, data->offset)
1946 <= 0) {
1947 SLOGE("Error reading real_blkdev %s for inplace encrypt",
1948 data->real_blkdev);
1949 return -1;
1950 }
1951
1952 if (pwrite64(data->cryptofd, data->buffer,
1953 info.block_size * data->count, data->offset)
1954 <= 0) {
1955 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
1956 data->crypto_blkdev);
1957 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08001958 } else {
1959 SLOGI("Encrypted %d blocks at sector %lld",
1960 data->count, data->offset / info.block_size * CRYPT_SECTOR_SIZE);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001961 }
1962
1963 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08001964 data->last_written_sector = (data->offset + data->count)
1965 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001966 return 0;
1967}
1968
1969static int encrypt_groups(struct encryptGroupsData* data)
1970{
1971 unsigned int i;
1972 u8 *block_bitmap = 0;
1973 unsigned int block;
1974 off64_t ret;
1975 int rc = -1;
1976
1977 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
1978 if (!data->buffer) {
1979 SLOGE("Failed to allocate crypto buffer");
1980 goto errout;
1981 }
1982
1983 block_bitmap = malloc(info.block_size);
1984 if (!block_bitmap) {
1985 SLOGE("failed to allocate block bitmap");
1986 goto errout;
1987 }
1988
1989 for (i = 0; i < aux_info.groups; ++i) {
1990 SLOGI("Encrypting group %d", i);
1991
1992 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
1993 u32 block_count = min(info.blocks_per_group,
1994 aux_info.len_blocks - first_block);
1995
1996 off64_t offset = (u64)info.block_size
1997 * aux_info.bg_desc[i].bg_block_bitmap;
1998
1999 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2000 if (ret != (int)info.block_size) {
2001 SLOGE("failed to read all of block group bitmap %d", i);
2002 goto errout;
2003 }
2004
2005 offset = (u64)info.block_size * first_block;
2006
2007 data->count = 0;
2008
2009 for (block = 0; block < block_count; block++) {
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002010 int used = bitmap_get_bit(block_bitmap, block);
2011 update_progress(data, used);
2012 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002013 if (data->count == 0) {
2014 data->offset = offset;
2015 }
2016 data->count++;
2017 } else {
2018 if (flush_outstanding_data(data)) {
2019 goto errout;
2020 }
2021 }
2022
2023 offset += info.block_size;
2024
2025 /* Write data if we are aligned or buffer size reached */
2026 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2027 || data->count == BLOCKS_AT_A_TIME) {
2028 if (flush_outstanding_data(data)) {
2029 goto errout;
2030 }
2031 }
Paul Lawrence87999172014-02-20 12:21:31 -08002032
2033 if (!is_battery_ok()) {
2034 SLOGE("Stopping encryption due to low battery");
2035 rc = 0;
2036 goto errout;
2037 }
2038
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002039 }
2040 if (flush_outstanding_data(data)) {
2041 goto errout;
2042 }
2043 }
2044
Paul Lawrence87999172014-02-20 12:21:31 -08002045 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002046 rc = 0;
2047
2048errout:
2049 free(data->buffer);
2050 free(block_bitmap);
2051 return rc;
2052}
2053
2054static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2055 char *real_blkdev,
2056 off64_t size,
2057 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002058 off64_t tot_size,
2059 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002060{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002061 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002062 struct encryptGroupsData data;
2063 int rc = -1;
2064
Paul Lawrence87999172014-02-20 12:21:31 -08002065 if (previously_encrypted_upto > *size_already_done) {
2066 SLOGD("Not fast encrypting since resuming part way through");
2067 return -1;
2068 }
2069
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002070 memset(&data, 0, sizeof(data));
2071 data.real_blkdev = real_blkdev;
2072 data.crypto_blkdev = crypto_blkdev;
2073
2074 if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
2075 SLOGE("Error opening real_blkdev %s for inplace encrypt\n",
2076 real_blkdev);
2077 goto errout;
2078 }
2079
2080 if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
2081 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n",
2082 crypto_blkdev);
2083 goto errout;
2084 }
2085
2086 if (setjmp(setjmp_env)) {
2087 SLOGE("Reading extent caused an exception");
2088 goto errout;
2089 }
2090
2091 if (read_ext(data.realfd, 0) != 0) {
2092 SLOGE("Failed to read extent");
2093 goto errout;
2094 }
2095
2096 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2097 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2098 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2099
2100 SLOGI("Encrypting filesystem in place...");
2101
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002102 data.tot_used_blocks = data.numblocks;
2103 for (i = 0; i < aux_info.groups; ++i) {
2104 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2105 }
2106
2107 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002108 data.cur_pct = 0;
2109
2110 rc = encrypt_groups(&data);
2111 if (rc) {
2112 SLOGE("Error encrypting groups");
2113 goto errout;
2114 }
2115
Paul Lawrence87999172014-02-20 12:21:31 -08002116 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002117 rc = 0;
2118
2119errout:
2120 close(data.realfd);
2121 close(data.cryptofd);
2122
2123 return rc;
2124}
2125
2126static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2127 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002128 off64_t tot_size,
2129 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002130{
2131 int realfd, cryptofd;
2132 char *buf[CRYPT_INPLACE_BUFSIZE];
2133 int rc = -1;
2134 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002135 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002136 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002137
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002138 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
2139 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
2140 return -1;
2141 }
2142
2143 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
2144 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
2145 close(realfd);
2146 return -1;
2147 }
2148
2149 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2150 * The size passed in is the number of 512 byte sectors in the filesystem.
2151 * So compute the number of whole 4K blocks we should read/write,
2152 * and the remainder.
2153 */
2154 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2155 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002156 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2157 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002158
2159 SLOGE("Encrypting filesystem in place...");
2160
Paul Lawrence87999172014-02-20 12:21:31 -08002161 i = previously_encrypted_upto + 1 - *size_already_done;
2162
2163 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2164 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2165 goto errout;
2166 }
2167
2168 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2169 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2170 goto errout;
2171 }
2172
2173 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2174 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2175 SLOGE("Error reading initial sectors from real_blkdev %s for "
2176 "inplace encrypt\n", crypto_blkdev);
2177 goto errout;
2178 }
2179 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2180 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2181 "inplace encrypt\n", crypto_blkdev);
2182 goto errout;
2183 } else {
2184 SLOGI("Encrypted 1 block at %lld", i);
2185 }
2186 }
2187
Ken Sumrall29d8da82011-05-18 17:20:07 -07002188 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002189 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002190 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002191 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002192 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002193 if (new_pct > cur_pct) {
2194 char buf[8];
2195
2196 cur_pct = new_pct;
2197 snprintf(buf, sizeof(buf), "%lld", cur_pct);
2198 property_set("vold.encrypt_progress", buf);
2199 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002200 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002201 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002202 goto errout;
2203 }
2204 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002205 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2206 goto errout;
2207 } else {
2208 SLOGD("Encrypted %d block at %lld",
2209 CRYPT_SECTORS_PER_BUFSIZE,
2210 i * CRYPT_SECTORS_PER_BUFSIZE);
2211 }
2212
2213 if (!is_battery_ok()) {
2214 SLOGE("Stopping encryption due to low battery");
2215 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2216 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002217 goto errout;
2218 }
2219 }
2220
2221 /* Do any remaining sectors */
2222 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002223 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2224 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002225 goto errout;
2226 }
Paul Lawrence87999172014-02-20 12:21:31 -08002227 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2228 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002229 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002230 } else {
2231 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002232 }
2233 }
2234
Ken Sumrall29d8da82011-05-18 17:20:07 -07002235 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002236 rc = 0;
2237
2238errout:
2239 close(realfd);
2240 close(cryptofd);
2241
2242 return rc;
2243}
2244
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002245static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2246 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002247 off64_t tot_size,
2248 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002249{
Paul Lawrence87999172014-02-20 12:21:31 -08002250 if (previously_encrypted_upto) {
2251 SLOGD("Continuing encryption from %lld", previously_encrypted_upto);
2252 }
2253
2254 if (*size_already_done + size < previously_encrypted_upto) {
2255 *size_already_done += size;
2256 return 0;
2257 }
2258
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002259 if (cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002260 size, size_already_done,
2261 tot_size, previously_encrypted_upto) == 0) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002262 return 0;
2263 }
2264
2265 return cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002266 size, size_already_done, tot_size,
2267 previously_encrypted_upto);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002268}
2269
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002270#define CRYPTO_ENABLE_WIPE 1
2271#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002272
2273#define FRAMEWORK_BOOT_WAIT 60
2274
Ken Sumrall29d8da82011-05-18 17:20:07 -07002275static inline int should_encrypt(struct volume_info *volume)
2276{
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002277 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
Ken Sumrall29d8da82011-05-18 17:20:07 -07002278 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
2279}
2280
Paul Lawrence87999172014-02-20 12:21:31 -08002281static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2282{
2283 int fd = open(filename, O_RDONLY);
2284 if (fd == -1) {
2285 SLOGE("Error opening file %s", filename);
2286 return -1;
2287 }
2288
2289 char block[CRYPT_INPLACE_BUFSIZE];
2290 memset(block, 0, sizeof(block));
2291 if (unix_read(fd, block, sizeof(block)) < 0) {
2292 SLOGE("Error reading file %s", filename);
2293 close(fd);
2294 return -1;
2295 }
2296
2297 close(fd);
2298
2299 SHA256_CTX c;
2300 SHA256_Init(&c);
2301 SHA256_Update(&c, block, sizeof(block));
2302 SHA256_Final(buf, &c);
2303
2304 return 0;
2305}
2306
2307static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2308 char *crypto_blkdev, char *real_blkdev,
2309 int previously_encrypted_upto)
2310{
2311 off64_t cur_encryption_done=0, tot_encryption_size=0;
2312 int i, rc = -1;
2313
2314 if (!is_battery_ok()) {
2315 SLOGE("Stopping encryption due to low battery");
2316 return 0;
2317 }
2318
2319 /* The size of the userdata partition, and add in the vold volumes below */
2320 tot_encryption_size = crypt_ftr->fs_size;
2321
2322 if (how == CRYPTO_ENABLE_WIPE) {
2323 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, EXT4_FS);
2324 } else if (how == CRYPTO_ENABLE_INPLACE) {
2325 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2326 crypt_ftr->fs_size, &cur_encryption_done,
2327 tot_encryption_size,
2328 previously_encrypted_upto);
2329
2330 if (!rc && cur_encryption_done != (off64_t)crypt_ftr->fs_size) {
2331 crypt_ftr->encrypted_upto = cur_encryption_done;
2332 }
2333
2334 if (!rc && !crypt_ftr->encrypted_upto) {
2335 /* The inplace routine never actually sets the progress to 100% due
2336 * to the round down nature of integer division, so set it here */
2337 property_set("vold.encrypt_progress", "100");
2338 }
2339 } else {
2340 /* Shouldn't happen */
2341 SLOGE("cryptfs_enable: internal error, unknown option\n");
2342 rc = -1;
2343 }
2344
2345 return rc;
2346}
2347
Paul Lawrence13486032014-02-03 13:28:11 -08002348int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
2349 int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002350{
2351 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002352 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07002353 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002354 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07002355 int rc=-1, fd, i, ret;
Paul Lawrence87999172014-02-20 12:21:31 -08002356 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002357 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002358 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002359 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002360 char key_loc[PROPERTY_VALUE_MAX];
2361 char fuse_sdcard[PROPERTY_VALUE_MAX];
2362 char *sd_mnt_point;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002363 int num_vols;
2364 struct volume_info *vol_list = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002365 off64_t previously_encrypted_upto = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002366
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002367 if (!strcmp(howarg, "wipe")) {
2368 how = CRYPTO_ENABLE_WIPE;
2369 } else if (! strcmp(howarg, "inplace")) {
2370 how = CRYPTO_ENABLE_INPLACE;
2371 } else {
2372 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002373 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002374 }
2375
Paul Lawrence87999172014-02-20 12:21:31 -08002376 /* See if an encryption was underway and interrupted */
2377 if (how == CRYPTO_ENABLE_INPLACE
2378 && get_crypt_ftr_and_key(&crypt_ftr) == 0
2379 && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
2380 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2381 crypt_ftr.encrypted_upto = 0;
2382 }
2383
2384 property_get("ro.crypto.state", encrypted_state, "");
2385 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2386 SLOGE("Device is already running encrypted, aborting");
2387 goto error_unencrypted;
2388 }
2389
2390 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2391 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002392 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002393
Ken Sumrall3ed82362011-01-28 23:31:16 -08002394 /* Get the size of the real block device */
2395 fd = open(real_blkdev, O_RDONLY);
2396 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
2397 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2398 goto error_unencrypted;
2399 }
2400 close(fd);
2401
2402 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002403 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002404 unsigned int fs_size_sec, max_fs_size_sec;
2405
2406 fs_size_sec = get_fs_size(real_blkdev);
Paul Lawrence87999172014-02-20 12:21:31 -08002407 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002408
2409 if (fs_size_sec > max_fs_size_sec) {
2410 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2411 goto error_unencrypted;
2412 }
2413 }
2414
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002415 /* Get a wakelock as this may take a while, and we don't want the
2416 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2417 * wants to keep the screen on, it can grab a full wakelock.
2418 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002419 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002420 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2421
Jeff Sharkey7382f812012-08-23 14:08:59 -07002422 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07002423 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07002424 if (!sd_mnt_point) {
2425 sd_mnt_point = getenv("EXTERNAL_STORAGE");
2426 }
2427 if (!sd_mnt_point) {
2428 sd_mnt_point = "/mnt/sdcard";
2429 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07002430
Paul Lawrence87999172014-02-20 12:21:31 -08002431 /* TODO
2432 * Currently do not have test devices with multiple encryptable volumes.
2433 * When we acquire some, re-add support.
2434 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002435 num_vols=vold_getNumDirectVolumes();
2436 vol_list = malloc(sizeof(struct volume_info) * num_vols);
2437 vold_getDirectVolumeList(vol_list);
2438
2439 for (i=0; i<num_vols; i++) {
2440 if (should_encrypt(&vol_list[i])) {
Paul Lawrence87999172014-02-20 12:21:31 -08002441 SLOGE("Cannot encrypt if there are multiple encryptable volumes"
2442 "%s\n", vol_list[i].label);
2443 goto error_unencrypted;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002444 }
2445 }
2446
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002447 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002448 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002449 */
2450 property_set("vold.decrypt", "trigger_shutdown_framework");
2451 SLOGD("Just asked init to shut down class main\n");
2452
Ken Sumrall425524d2012-06-14 20:55:28 -07002453 if (vold_unmountAllAsecs()) {
2454 /* Just report the error. If any are left mounted,
2455 * umounting /data below will fail and handle the error.
2456 */
2457 SLOGE("Error unmounting internal asecs");
2458 }
2459
Ken Sumrall29d8da82011-05-18 17:20:07 -07002460 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
2461 if (!strcmp(fuse_sdcard, "true")) {
2462 /* This is a device using the fuse layer to emulate the sdcard semantics
2463 * on top of the userdata partition. vold does not manage it, it is managed
2464 * by the sdcard service. The sdcard service was killed by the property trigger
2465 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
2466 * unlike the case for vold managed devices above.
2467 */
2468 if (wait_and_unmount(sd_mnt_point)) {
2469 goto error_shutting_down;
2470 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002471 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002472
2473 /* Now unmount the /data partition. */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002474 if (wait_and_unmount(DATA_MNT_POINT)) {
JP Abgrall502dc742013-11-01 13:06:20 -07002475 if (allow_reboot) {
2476 goto error_shutting_down;
2477 } else {
2478 goto error_unencrypted;
2479 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002480 }
2481
2482 /* Do extra work for a better UX when doing the long inplace encryption */
2483 if (how == CRYPTO_ENABLE_INPLACE) {
2484 /* Now that /data is unmounted, we need to mount a tmpfs
2485 * /data, set a property saying we're doing inplace encryption,
2486 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002487 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002488 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002489 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002490 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002491 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002492 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002493
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002494 /* restart the framework. */
2495 /* Create necessary paths on /data */
2496 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002497 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002498 }
2499
Ken Sumrall92736ef2012-10-17 20:57:14 -07002500 /* Ugh, shutting down the framework is not synchronous, so until it
2501 * can be fixed, this horrible hack will wait a moment for it all to
2502 * shut down before proceeding. Without it, some devices cannot
2503 * restart the graphics services.
2504 */
2505 sleep(2);
2506
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002507 /* startup service classes main and late_start */
2508 property_set("vold.decrypt", "trigger_restart_min_framework");
2509 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002510
Ken Sumrall7df84122011-01-18 14:04:08 -08002511 /* OK, the framework is restarted and will soon be showing a
2512 * progress bar. Time to setup an encrypted mapping, and
2513 * either write a new filesystem, or encrypt in place updating
2514 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002515 */
2516 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002517
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002518 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002519 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence87999172014-02-20 12:21:31 -08002520 if (previously_encrypted_upto == 0) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002521 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2522 goto error_shutting_down;
2523 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002524
Paul Lawrence87999172014-02-20 12:21:31 -08002525 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2526 crypt_ftr.fs_size = nr_sec
2527 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2528 } else {
2529 crypt_ftr.fs_size = nr_sec;
2530 }
2531 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
2532 crypt_ftr.crypt_type = crypt_type;
2533 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002534
Paul Lawrence87999172014-02-20 12:21:31 -08002535 /* Make an encrypted master key */
2536 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
2537 SLOGE("Cannot create encrypted master key\n");
2538 goto error_shutting_down;
2539 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002540
Paul Lawrence87999172014-02-20 12:21:31 -08002541 /* Write the key to the end of the partition */
2542 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002543
Paul Lawrence87999172014-02-20 12:21:31 -08002544 /* If any persistent data has been remembered, save it.
2545 * If none, create a valid empty table and save that.
2546 */
2547 if (!persist_data) {
2548 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
2549 if (pdata) {
2550 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2551 persist_data = pdata;
2552 }
2553 }
2554 if (persist_data) {
2555 save_persistent_data();
2556 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002557 }
2558
JP Abgrall7bdfa522013-11-15 13:42:56 -08002559 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002560 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
2561 "userdata");
2562
Paul Lawrence87999172014-02-20 12:21:31 -08002563 /* If we are continuing, check checksums match */
2564 rc = 0;
2565 if (previously_encrypted_upto) {
2566 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2567 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002568
Paul Lawrence87999172014-02-20 12:21:31 -08002569 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2570 sizeof(hash_first_block)) != 0) {
2571 SLOGE("Checksums do not match - trigger wipe");
2572 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002573 }
2574 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002575
Paul Lawrence87999172014-02-20 12:21:31 -08002576 if (!rc) {
2577 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
2578 crypto_blkdev, real_blkdev,
2579 previously_encrypted_upto);
2580 }
2581
2582 /* Calculate checksum if we are not finished */
2583 if (!rc && crypt_ftr.encrypted_upto) {
2584 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2585 crypt_ftr.hash_first_block);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002586 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002587 SLOGE("Error calculating checksum for continuing encryption");
2588 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002589 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002590 }
2591
2592 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002593 delete_crypto_blk_dev("userdata");
Ken Sumrall29d8da82011-05-18 17:20:07 -07002594
2595 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002596
2597 if (! rc) {
2598 /* Success */
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002599
Ken Sumralld33d4172011-02-01 00:49:13 -08002600 /* Clear the encryption in progres flag in the footer */
Paul Lawrence87999172014-02-20 12:21:31 -08002601 if (!crypt_ftr.encrypted_upto) {
2602 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
2603 } else {
2604 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2605 crypt_ftr.encrypted_upto);
2606 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002607 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002608
Ken Sumrall29d8da82011-05-18 17:20:07 -07002609 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08002610 /* Partially encrypted - ensure writes are flushed to ssd */
2611
2612 if (!crypt_ftr.encrypted_upto) {
2613 cryptfs_reboot(reboot);
2614 } else {
2615 cryptfs_reboot(shutdown);
2616 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002617 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002618 char value[PROPERTY_VALUE_MAX];
2619
Ken Sumrall319369a2012-06-27 16:30:18 -07002620 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002621 if (!strcmp(value, "1")) {
2622 /* wipe data if encryption failed */
2623 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
2624 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07002625 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002626 if (fd >= 0) {
2627 write(fd, "--wipe_data", strlen("--wipe_data") + 1);
2628 close(fd);
2629 } else {
2630 SLOGE("could not open /cache/recovery/command\n");
2631 }
Paul Lawrence87999172014-02-20 12:21:31 -08002632 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002633 } else {
2634 /* set property to trigger dialog */
2635 property_set("vold.encrypt_progress", "error_partially_encrypted");
2636 release_wake_lock(lockid);
2637 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002638 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002639 }
2640
Ken Sumrall3ed82362011-01-28 23:31:16 -08002641 /* hrm, the encrypt step claims success, but the reboot failed.
2642 * This should not happen.
2643 * Set the property and return. Hope the framework can deal with it.
2644 */
2645 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002646 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002647 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002648
2649error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07002650 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002651 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002652 if (lockid[0]) {
2653 release_wake_lock(lockid);
2654 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002655 return -1;
2656
2657error_shutting_down:
2658 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2659 * but the framework is stopped and not restarted to show the error, so it's up to
2660 * vold to restart the system.
2661 */
2662 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08002663 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002664
2665 /* shouldn't get here */
2666 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07002667 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002668 if (lockid[0]) {
2669 release_wake_lock(lockid);
2670 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002671 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002672}
2673
Paul Lawrence45f10532014-04-04 18:11:56 +00002674int cryptfs_enable(char *howarg, int type, char *passwd, int allow_reboot)
Paul Lawrence13486032014-02-03 13:28:11 -08002675{
Paul Lawrence45f10532014-04-04 18:11:56 +00002676 return cryptfs_enable_internal(howarg, type, passwd, allow_reboot);
Paul Lawrence13486032014-02-03 13:28:11 -08002677}
2678
2679int cryptfs_enable_default(char *howarg, int allow_reboot)
2680{
2681 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
2682 DEFAULT_PASSWORD, allow_reboot);
2683}
2684
2685int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002686{
2687 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002688 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002689
2690 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002691 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002692 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002693 return -1;
2694 }
2695
Paul Lawrencef4faa572014-01-29 13:31:03 -08002696 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2697 SLOGE("Invalid crypt_type %d", crypt_type);
2698 return -1;
2699 }
2700
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002701 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002702 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002703 SLOGE("Error getting crypt footer and key");
2704 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002705 }
2706
Paul Lawrencef4faa572014-01-29 13:31:03 -08002707 crypt_ftr.crypt_type = crypt_type;
2708
2709 encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
2710 : newpw,
2711 crypt_ftr.salt,
2712 saved_master_key,
2713 crypt_ftr.master_key,
2714 &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002715
Jason parks70a4b3f2011-01-28 10:10:47 -06002716 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002717 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002718
2719 return 0;
2720}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002721
2722static int persist_get_key(char *fieldname, char *value)
2723{
2724 unsigned int i;
2725
2726 if (persist_data == NULL) {
2727 return -1;
2728 }
2729 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2730 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2731 /* We found it! */
2732 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2733 return 0;
2734 }
2735 }
2736
2737 return -1;
2738}
2739
2740static int persist_set_key(char *fieldname, char *value, int encrypted)
2741{
2742 unsigned int i;
2743 unsigned int num;
2744 struct crypt_mnt_ftr crypt_ftr;
2745 unsigned int max_persistent_entries;
2746 unsigned int dsize;
2747
2748 if (persist_data == NULL) {
2749 return -1;
2750 }
2751
2752 /* If encrypted, use the values from the crypt_ftr, otherwise
2753 * use the values for the current spec.
2754 */
2755 if (encrypted) {
2756 if(get_crypt_ftr_and_key(&crypt_ftr)) {
2757 return -1;
2758 }
2759 dsize = crypt_ftr.persist_data_size;
2760 } else {
2761 dsize = CRYPT_PERSIST_DATA_SIZE;
2762 }
2763 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2764 sizeof(struct crypt_persist_entry);
2765
2766 num = persist_data->persist_valid_entries;
2767
2768 for (i = 0; i < num; i++) {
2769 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2770 /* We found an existing entry, update it! */
2771 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2772 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2773 return 0;
2774 }
2775 }
2776
2777 /* We didn't find it, add it to the end, if there is room */
2778 if (persist_data->persist_valid_entries < max_persistent_entries) {
2779 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2780 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2781 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2782 persist_data->persist_valid_entries++;
2783 return 0;
2784 }
2785
2786 return -1;
2787}
2788
2789/* Return the value of the specified field. */
2790int cryptfs_getfield(char *fieldname, char *value, int len)
2791{
2792 char temp_value[PROPERTY_VALUE_MAX];
2793 char real_blkdev[MAXPATHLEN];
2794 /* 0 is success, 1 is not encrypted,
2795 * -1 is value not set, -2 is any other error
2796 */
2797 int rc = -2;
2798
2799 if (persist_data == NULL) {
2800 load_persistent_data();
2801 if (persist_data == NULL) {
2802 SLOGE("Getfield error, cannot load persistent data");
2803 goto out;
2804 }
2805 }
2806
2807 if (!persist_get_key(fieldname, temp_value)) {
2808 /* We found it, copy it to the caller's buffer and return */
2809 strlcpy(value, temp_value, len);
2810 rc = 0;
2811 } else {
2812 /* Sadness, it's not there. Return the error */
2813 rc = -1;
2814 }
2815
2816out:
2817 return rc;
2818}
2819
2820/* Set the value of the specified field. */
2821int cryptfs_setfield(char *fieldname, char *value)
2822{
2823 struct crypt_persist_data stored_pdata;
2824 struct crypt_persist_data *pdata_p;
2825 struct crypt_mnt_ftr crypt_ftr;
2826 char encrypted_state[PROPERTY_VALUE_MAX];
2827 /* 0 is success, -1 is an error */
2828 int rc = -1;
2829 int encrypted = 0;
2830
2831 if (persist_data == NULL) {
2832 load_persistent_data();
2833 if (persist_data == NULL) {
2834 SLOGE("Setfield error, cannot load persistent data");
2835 goto out;
2836 }
2837 }
2838
2839 property_get("ro.crypto.state", encrypted_state, "");
2840 if (!strcmp(encrypted_state, "encrypted") ) {
2841 encrypted = 1;
2842 }
2843
2844 if (persist_set_key(fieldname, value, encrypted)) {
2845 goto out;
2846 }
2847
2848 /* If we are running encrypted, save the persistent data now */
2849 if (encrypted) {
2850 if (save_persistent_data()) {
2851 SLOGE("Setfield error, cannot save persistent data");
2852 goto out;
2853 }
2854 }
2855
2856 rc = 0;
2857
2858out:
2859 return rc;
2860}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002861
2862/* Checks userdata. Attempt to mount the volume if default-
2863 * encrypted.
2864 * On success trigger next init phase and return 0.
2865 * Currently do not handle failure - see TODO below.
2866 */
2867int cryptfs_mount_default_encrypted(void)
2868{
2869 char decrypt_state[PROPERTY_VALUE_MAX];
2870 property_get("vold.decrypt", decrypt_state, "0");
2871 if (!strcmp(decrypt_state, "0")) {
2872 SLOGE("Not encrypted - should not call here");
2873 } else {
2874 int crypt_type = cryptfs_get_password_type();
2875 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2876 SLOGE("Bad crypt type - error");
2877 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2878 SLOGD("Password is not default - "
2879 "starting min framework to prompt");
2880 property_set("vold.decrypt", "trigger_restart_min_framework");
2881 return 0;
2882 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2883 SLOGD("Password is default - restarting filesystem");
2884 cryptfs_restart_internal(0);
2885 return 0;
2886 } else {
2887 SLOGE("Encrypted, default crypt type but can't decrypt");
2888 }
2889 }
2890
2891 /** @TODO make sure we factory wipe in this situation
2892 * In general if we got here there is no recovery
2893 */
2894 return 0;
2895}
2896
2897/* Returns type of the password, default, pattern, pin or password.
2898 */
2899int cryptfs_get_password_type(void)
2900{
2901 struct crypt_mnt_ftr crypt_ftr;
2902
2903 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2904 SLOGE("Error getting crypt footer and key\n");
2905 return -1;
2906 }
2907
2908 return crypt_ftr.crypt_type;
2909}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002910
Paul Lawrence399317e2014-03-10 13:20:50 -07002911char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002912{
Paul Lawrence399317e2014-03-10 13:20:50 -07002913 struct timespec now;
2914 clock_gettime(CLOCK_MONOTONIC, &now);
2915 if (now.tv_sec < password_expiry_time) {
2916 return password;
2917 } else {
2918 cryptfs_clear_password();
2919 return 0;
2920 }
2921}
2922
2923void cryptfs_clear_password()
2924{
2925 if (password) {
2926 size_t len = strlen(password);
2927 memset(password, 0, len);
2928 free(password);
2929 password = 0;
2930 password_expiry_time = 0;
2931 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002932}