blob: 93680e5f97a41b26538a97b2f011cbd1fde2efdb [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
23#include <sys/types.h>
Ken Sumralle550f782013-08-20 13:48:23 -070024#include <sys/wait.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080025#include <sys/stat.h>
Paul Lawrencef4faa572014-01-29 13:31:03 -080026#include <ctype.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080027#include <fcntl.h>
Elliott Hughes73737162014-06-25 17:27:42 -070028#include <inttypes.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080029#include <unistd.h>
30#include <stdio.h>
31#include <sys/ioctl.h>
32#include <linux/dm-ioctl.h>
33#include <libgen.h>
34#include <stdlib.h>
35#include <sys/param.h>
36#include <string.h>
37#include <sys/mount.h>
38#include <openssl/evp.h>
39#include <errno.h>
Ken Sumrall3ed82362011-01-28 23:31:16 -080040#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070041#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070042#include <fs_mgr.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080043#include "cryptfs.h"
44#define LOG_TAG "Cryptfs"
45#include "cutils/log.h"
46#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070047#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080048#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070049#include <logwrap/logwrap.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070050#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070051#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070052#include "crypto_scrypt.h"
Paul Lawrenceae59fe62014-01-21 08:23:27 -080053#include "ext4_utils.h"
Paul Lawrence87999172014-02-20 12:21:31 -080054#include "CheckBattery.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080055
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070056#include <hardware/keymaster.h>
57
Mark Salyzyn3e971272014-01-21 13:27:04 -080058#define UNUSED __attribute__((unused))
59
Mark Salyzyn5eecc442014-02-12 14:16:14 -080060#define UNUSED __attribute__((unused))
61
Ken Sumrall8f869aa2010-12-03 03:47:09 -080062#define DM_CRYPT_BUF_SIZE 4096
63
Jason parks70a4b3f2011-01-28 10:10:47 -060064#define HASH_COUNT 2000
65#define KEY_LEN_BYTES 16
66#define IV_LEN_BYTES 16
67
Ken Sumrall29d8da82011-05-18 17:20:07 -070068#define KEY_IN_FOOTER "footer"
69
Paul Lawrencef4faa572014-01-29 13:31:03 -080070// "default_password" encoded into hex (d=0x64 etc)
71#define DEFAULT_PASSWORD "64656661756c745f70617373776f7264"
72
Ken Sumrall29d8da82011-05-18 17:20:07 -070073#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070074#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070075
Ken Sumralle919efe2012-09-29 17:07:41 -070076#define TABLE_LOAD_RETRIES 10
77
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070078#define RSA_DEFAULT_KEY_SIZE 2048
79#define RSA_DEFAULT_EXPONENT 0x10001
80
Ken Sumrall8f869aa2010-12-03 03:47:09 -080081char *me = "cryptfs";
82
Jason parks70a4b3f2011-01-28 10:10:47 -060083static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070084static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060085static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -070086static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -080087
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070088static int keymaster_init(keymaster_device_t **keymaster_dev)
89{
90 int rc;
91
92 const hw_module_t* mod;
93 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
94 if (rc) {
95 ALOGE("could not find any keystore module");
96 goto out;
97 }
98
99 rc = keymaster_open(mod, keymaster_dev);
100 if (rc) {
101 ALOGE("could not open keymaster device in %s (%s)",
102 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
103 goto out;
104 }
105
106 return 0;
107
108out:
109 *keymaster_dev = NULL;
110 return rc;
111}
112
113/* Should we use keymaster? */
114static int keymaster_check_compatibility()
115{
116 keymaster_device_t *keymaster_dev = 0;
117 int rc = 0;
118
119 if (keymaster_init(&keymaster_dev)) {
120 SLOGE("Failed to init keymaster");
121 rc = -1;
122 goto out;
123 }
124
Paul Lawrence8c008392014-05-06 14:02:48 -0700125 SLOGI("keymaster version is %d", keymaster_dev->common.module->module_api_version);
126
127 if (keymaster_dev->common.module->module_api_version
128 < KEYMASTER_MODULE_API_VERSION_0_3) {
129 rc = 0;
130 goto out;
131 }
132
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700133 if (keymaster_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE) {
134 rc = 1;
135 }
136
137out:
138 keymaster_close(keymaster_dev);
139 return rc;
140}
141
142/* Create a new keymaster key and store it in this footer */
143static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
144{
145 uint8_t* key = 0;
146 keymaster_device_t *keymaster_dev = 0;
147
148 if (keymaster_init(&keymaster_dev)) {
149 SLOGE("Failed to init keymaster");
150 return -1;
151 }
152
153 int rc = 0;
154
155 keymaster_rsa_keygen_params_t params;
156 memset(&params, '\0', sizeof(params));
157 params.public_exponent = RSA_DEFAULT_EXPONENT;
158 params.modulus_size = RSA_DEFAULT_KEY_SIZE;
159
160 size_t key_size;
161 if (keymaster_dev->generate_keypair(keymaster_dev, TYPE_RSA, &params,
162 &key, &key_size)) {
163 SLOGE("Failed to generate keypair");
164 rc = -1;
165 goto out;
166 }
167
168 if (key_size > KEYMASTER_BLOB_SIZE) {
169 SLOGE("Keymaster key too large for crypto footer");
170 rc = -1;
171 goto out;
172 }
173
174 memcpy(ftr->keymaster_blob, key, key_size);
175 ftr->keymaster_blob_size = key_size;
176
177out:
178 keymaster_close(keymaster_dev);
179 free(key);
180 return rc;
181}
182
183/* This signs the given object using the keymaster key */
184static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
185 const unsigned char *object,
186 const size_t object_size,
187 unsigned char **signature,
188 size_t *signature_size)
189{
190 int rc = 0;
191 keymaster_device_t *keymaster_dev = 0;
192 if (keymaster_init(&keymaster_dev)) {
193 SLOGE("Failed to init keymaster");
194 return -1;
195 }
196
197 /* We currently set the digest type to DIGEST_NONE because it's the
198 * only supported value for keymaster. A similar issue exists with
199 * PADDING_NONE. Long term both of these should likely change.
200 */
201 keymaster_rsa_sign_params_t params;
202 params.digest_type = DIGEST_NONE;
203 params.padding_type = PADDING_NONE;
204
205 rc = keymaster_dev->sign_data(keymaster_dev,
206 &params,
207 ftr->keymaster_blob,
208 ftr->keymaster_blob_size,
209 object,
210 object_size,
211 signature,
212 signature_size);
213
214 keymaster_close(keymaster_dev);
215 return rc;
216}
217
Paul Lawrence399317e2014-03-10 13:20:50 -0700218/* Store password when userdata is successfully decrypted and mounted.
219 * Cleared by cryptfs_clear_password
220 *
221 * To avoid a double prompt at boot, we need to store the CryptKeeper
222 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
223 * Since the entire framework is torn down and rebuilt after encryption,
224 * we have to use a daemon or similar to store the password. Since vold
225 * is secured against IPC except from system processes, it seems a reasonable
226 * place to store this.
227 *
228 * password should be cleared once it has been used.
229 *
230 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800231 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700232static char* password = 0;
233static int password_expiry_time = 0;
234static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800235
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800236extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800237
Paul Lawrence87999172014-02-20 12:21:31 -0800238enum RebootType {reboot, recovery, shutdown};
239static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700240{
Paul Lawrence87999172014-02-20 12:21:31 -0800241 switch(rt) {
242 case reboot:
243 property_set(ANDROID_RB_PROPERTY, "reboot");
244 break;
245
246 case recovery:
247 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
248 break;
249
250 case shutdown:
251 property_set(ANDROID_RB_PROPERTY, "shutdown");
252 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700253 }
Paul Lawrence87999172014-02-20 12:21:31 -0800254
Ken Sumralladfba362013-06-04 16:37:52 -0700255 sleep(20);
256
257 /* Shouldn't get here, reboot should happen before sleep times out */
258 return;
259}
260
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800261static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
262{
263 memset(io, 0, dataSize);
264 io->data_size = dataSize;
265 io->data_start = sizeof(struct dm_ioctl);
266 io->version[0] = 4;
267 io->version[1] = 0;
268 io->version[2] = 0;
269 io->flags = flags;
270 if (name) {
271 strncpy(io->name, name, sizeof(io->name));
272 }
273}
274
Kenny Rootc4c70f12013-06-14 12:11:38 -0700275/**
276 * Gets the default device scrypt parameters for key derivation time tuning.
277 * The parameters should lead to about one second derivation time for the
278 * given device.
279 */
280static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
281 const int default_params[] = SCRYPT_DEFAULTS;
282 int params[] = SCRYPT_DEFAULTS;
283 char paramstr[PROPERTY_VALUE_MAX];
284 char *token;
285 char *saveptr;
286 int i;
287
288 property_get(SCRYPT_PROP, paramstr, "");
289 if (paramstr[0] != '\0') {
290 /*
291 * The token we're looking for should be three integers separated by
292 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
293 */
Kenny Root2947e342013-08-14 15:54:49 -0700294 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
295 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700296 i++, token = strtok_r(NULL, ":", &saveptr)) {
297 char *endptr;
298 params[i] = strtol(token, &endptr, 10);
299
300 /*
301 * Check that there was a valid number and it's 8-bit. If not,
302 * break out and the end check will take the default values.
303 */
304 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
305 break;
306 }
307 }
308
309 /*
310 * If there were not enough tokens or a token was malformed (not an
311 * integer), it will end up here and the default parameters can be
312 * taken.
313 */
314 if ((i != 3) || (token != NULL)) {
315 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
316 memcpy(params, default_params, sizeof(params));
317 }
318 }
319
320 ftr->N_factor = params[0];
321 ftr->r_factor = params[1];
322 ftr->p_factor = params[2];
323}
324
Ken Sumrall3ed82362011-01-28 23:31:16 -0800325static unsigned int get_fs_size(char *dev)
326{
327 int fd, block_size;
328 struct ext4_super_block sb;
329 off64_t len;
330
331 if ((fd = open(dev, O_RDONLY)) < 0) {
332 SLOGE("Cannot open device to get filesystem size ");
333 return 0;
334 }
335
336 if (lseek64(fd, 1024, SEEK_SET) < 0) {
337 SLOGE("Cannot seek to superblock");
338 return 0;
339 }
340
341 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
342 SLOGE("Cannot read superblock");
343 return 0;
344 }
345
346 close(fd);
347
348 block_size = 1024 << sb.s_log_block_size;
349 /* compute length in bytes */
350 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
351
352 /* return length in sectors */
353 return (unsigned int) (len / 512);
354}
355
Ken Sumrall160b4d62013-04-22 12:15:39 -0700356static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
357{
358 static int cached_data = 0;
359 static off64_t cached_off = 0;
360 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
361 int fd;
362 char key_loc[PROPERTY_VALUE_MAX];
363 char real_blkdev[PROPERTY_VALUE_MAX];
364 unsigned int nr_sec;
365 int rc = -1;
366
367 if (!cached_data) {
368 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
369
370 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
371 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
372 SLOGE("Cannot open real block device %s\n", real_blkdev);
373 return -1;
374 }
375
376 if ((nr_sec = get_blkdev_size(fd))) {
377 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
378 * encryption info footer and key, and plenty of bytes to spare for future
379 * growth.
380 */
381 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
382 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
383 cached_data = 1;
384 } else {
385 SLOGE("Cannot get size of block device %s\n", real_blkdev);
386 }
387 close(fd);
388 } else {
389 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
390 cached_off = 0;
391 cached_data = 1;
392 }
393 }
394
395 if (cached_data) {
396 if (metadata_fname) {
397 *metadata_fname = cached_metadata_fname;
398 }
399 if (off) {
400 *off = cached_off;
401 }
402 rc = 0;
403 }
404
405 return rc;
406}
407
Ken Sumralle8744072011-01-18 22:01:55 -0800408/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800409 * update the failed mount count but not change the key.
410 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700411static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800412{
413 int fd;
414 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700415 /* starting_off is set to the SEEK_SET offset
416 * where the crypto structure starts
417 */
418 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800419 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700420 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700421 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800422
Ken Sumrall160b4d62013-04-22 12:15:39 -0700423 if (get_crypt_ftr_info(&fname, &starting_off)) {
424 SLOGE("Unable to get crypt_ftr_info\n");
425 return -1;
426 }
427 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700428 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700429 return -1;
430 }
Ken Sumralle550f782013-08-20 13:48:23 -0700431 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
432 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700433 return -1;
434 }
435
436 /* Seek to the start of the crypt footer */
437 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
438 SLOGE("Cannot seek to real block device footer\n");
439 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800440 }
441
442 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
443 SLOGE("Cannot write real block device footer\n");
444 goto errout;
445 }
446
Ken Sumrall3be890f2011-09-14 16:53:46 -0700447 fstat(fd, &statbuf);
448 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700449 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700450 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800451 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800452 goto errout;
453 }
454 }
455
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800456 /* Success! */
457 rc = 0;
458
459errout:
460 close(fd);
461 return rc;
462
463}
464
Ken Sumrall160b4d62013-04-22 12:15:39 -0700465static inline int unix_read(int fd, void* buff, int len)
466{
467 return TEMP_FAILURE_RETRY(read(fd, buff, len));
468}
469
470static inline int unix_write(int fd, const void* buff, int len)
471{
472 return TEMP_FAILURE_RETRY(write(fd, buff, len));
473}
474
475static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
476{
477 memset(pdata, 0, len);
478 pdata->persist_magic = PERSIST_DATA_MAGIC;
479 pdata->persist_valid_entries = 0;
480}
481
482/* A routine to update the passed in crypt_ftr to the lastest version.
483 * fd is open read/write on the device that holds the crypto footer and persistent
484 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
485 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
486 */
487static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
488{
Kenny Root7434b312013-06-14 11:29:53 -0700489 int orig_major = crypt_ftr->major_version;
490 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700491
Kenny Root7434b312013-06-14 11:29:53 -0700492 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
493 struct crypt_persist_data *pdata;
494 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700495
Kenny Rootc4c70f12013-06-14 12:11:38 -0700496 SLOGW("upgrading crypto footer to 1.1");
497
Kenny Root7434b312013-06-14 11:29:53 -0700498 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
499 if (pdata == NULL) {
500 SLOGE("Cannot allocate persisent data\n");
501 return;
502 }
503 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
504
505 /* Need to initialize the persistent data area */
506 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
507 SLOGE("Cannot seek to persisent data offset\n");
508 return;
509 }
510 /* Write all zeros to the first copy, making it invalid */
511 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
512
513 /* Write a valid but empty structure to the second copy */
514 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
515 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
516
517 /* Update the footer */
518 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
519 crypt_ftr->persist_data_offset[0] = pdata_offset;
520 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
521 crypt_ftr->minor_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700522 }
523
Paul Lawrencef4faa572014-01-29 13:31:03 -0800524 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700525 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800526 /* But keep the old kdf_type.
527 * It will get updated later to KDF_SCRYPT after the password has been verified.
528 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700529 crypt_ftr->kdf_type = KDF_PBKDF2;
530 get_device_scrypt_params(crypt_ftr);
531 crypt_ftr->minor_version = 2;
532 }
533
Paul Lawrencef4faa572014-01-29 13:31:03 -0800534 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
535 SLOGW("upgrading crypto footer to 1.3");
536 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
537 crypt_ftr->minor_version = 3;
538 }
539
Kenny Root7434b312013-06-14 11:29:53 -0700540 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
541 if (lseek64(fd, offset, SEEK_SET) == -1) {
542 SLOGE("Cannot seek to crypt footer\n");
543 return;
544 }
545 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700546 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700547}
548
549
550static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800551{
552 int fd;
553 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700554 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800555 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700556 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700557 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800558
Ken Sumrall160b4d62013-04-22 12:15:39 -0700559 if (get_crypt_ftr_info(&fname, &starting_off)) {
560 SLOGE("Unable to get crypt_ftr_info\n");
561 return -1;
562 }
563 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700564 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700565 return -1;
566 }
567 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700568 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700569 return -1;
570 }
571
572 /* Make sure it's 16 Kbytes in length */
573 fstat(fd, &statbuf);
574 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
575 SLOGE("footer file %s is not the expected size!\n", fname);
576 goto errout;
577 }
578
579 /* Seek to the start of the crypt footer */
580 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
581 SLOGE("Cannot seek to real block device footer\n");
582 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800583 }
584
585 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
586 SLOGE("Cannot read real block device footer\n");
587 goto errout;
588 }
589
590 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700591 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800592 goto errout;
593 }
594
Kenny Rootc96a5f82013-06-14 12:08:28 -0700595 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
596 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
597 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800598 goto errout;
599 }
600
Kenny Rootc96a5f82013-06-14 12:08:28 -0700601 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
602 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
603 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800604 }
605
Ken Sumrall160b4d62013-04-22 12:15:39 -0700606 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
607 * copy on disk before returning.
608 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700609 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700610 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800611 }
612
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800613 /* Success! */
614 rc = 0;
615
616errout:
617 close(fd);
618 return rc;
619}
620
Ken Sumrall160b4d62013-04-22 12:15:39 -0700621static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
622{
623 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
624 crypt_ftr->persist_data_offset[1]) {
625 SLOGE("Crypt_ftr persist data regions overlap");
626 return -1;
627 }
628
629 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
630 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
631 return -1;
632 }
633
634 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
635 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
636 CRYPT_FOOTER_OFFSET) {
637 SLOGE("Persistent data extends past crypto footer");
638 return -1;
639 }
640
641 return 0;
642}
643
644static int load_persistent_data(void)
645{
646 struct crypt_mnt_ftr crypt_ftr;
647 struct crypt_persist_data *pdata = NULL;
648 char encrypted_state[PROPERTY_VALUE_MAX];
649 char *fname;
650 int found = 0;
651 int fd;
652 int ret;
653 int i;
654
655 if (persist_data) {
656 /* Nothing to do, we've already loaded or initialized it */
657 return 0;
658 }
659
660
661 /* If not encrypted, just allocate an empty table and initialize it */
662 property_get("ro.crypto.state", encrypted_state, "");
663 if (strcmp(encrypted_state, "encrypted") ) {
664 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
665 if (pdata) {
666 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
667 persist_data = pdata;
668 return 0;
669 }
670 return -1;
671 }
672
673 if(get_crypt_ftr_and_key(&crypt_ftr)) {
674 return -1;
675 }
676
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700677 if ((crypt_ftr.major_version < 1)
678 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700679 SLOGE("Crypt_ftr version doesn't support persistent data");
680 return -1;
681 }
682
683 if (get_crypt_ftr_info(&fname, NULL)) {
684 return -1;
685 }
686
687 ret = validate_persistent_data_storage(&crypt_ftr);
688 if (ret) {
689 return -1;
690 }
691
692 fd = open(fname, O_RDONLY);
693 if (fd < 0) {
694 SLOGE("Cannot open %s metadata file", fname);
695 return -1;
696 }
697
698 if (persist_data == NULL) {
699 pdata = malloc(crypt_ftr.persist_data_size);
700 if (pdata == NULL) {
701 SLOGE("Cannot allocate memory for persistent data");
702 goto err;
703 }
704 }
705
706 for (i = 0; i < 2; i++) {
707 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
708 SLOGE("Cannot seek to read persistent data on %s", fname);
709 goto err2;
710 }
711 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
712 SLOGE("Error reading persistent data on iteration %d", i);
713 goto err2;
714 }
715 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
716 found = 1;
717 break;
718 }
719 }
720
721 if (!found) {
722 SLOGI("Could not find valid persistent data, creating");
723 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
724 }
725
726 /* Success */
727 persist_data = pdata;
728 close(fd);
729 return 0;
730
731err2:
732 free(pdata);
733
734err:
735 close(fd);
736 return -1;
737}
738
739static int save_persistent_data(void)
740{
741 struct crypt_mnt_ftr crypt_ftr;
742 struct crypt_persist_data *pdata;
743 char *fname;
744 off64_t write_offset;
745 off64_t erase_offset;
746 int found = 0;
747 int fd;
748 int ret;
749
750 if (persist_data == NULL) {
751 SLOGE("No persistent data to save");
752 return -1;
753 }
754
755 if(get_crypt_ftr_and_key(&crypt_ftr)) {
756 return -1;
757 }
758
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700759 if ((crypt_ftr.major_version < 1)
760 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700761 SLOGE("Crypt_ftr version doesn't support persistent data");
762 return -1;
763 }
764
765 ret = validate_persistent_data_storage(&crypt_ftr);
766 if (ret) {
767 return -1;
768 }
769
770 if (get_crypt_ftr_info(&fname, NULL)) {
771 return -1;
772 }
773
774 fd = open(fname, O_RDWR);
775 if (fd < 0) {
776 SLOGE("Cannot open %s metadata file", fname);
777 return -1;
778 }
779
780 pdata = malloc(crypt_ftr.persist_data_size);
781 if (pdata == NULL) {
782 SLOGE("Cannot allocate persistant data");
783 goto err;
784 }
785
786 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
787 SLOGE("Cannot seek to read persistent data on %s", fname);
788 goto err2;
789 }
790
791 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
792 SLOGE("Error reading persistent data before save");
793 goto err2;
794 }
795
796 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
797 /* The first copy is the curent valid copy, so write to
798 * the second copy and erase this one */
799 write_offset = crypt_ftr.persist_data_offset[1];
800 erase_offset = crypt_ftr.persist_data_offset[0];
801 } else {
802 /* The second copy must be the valid copy, so write to
803 * the first copy, and erase the second */
804 write_offset = crypt_ftr.persist_data_offset[0];
805 erase_offset = crypt_ftr.persist_data_offset[1];
806 }
807
808 /* Write the new copy first, if successful, then erase the old copy */
809 if (lseek(fd, write_offset, SEEK_SET) < 0) {
810 SLOGE("Cannot seek to write persistent data");
811 goto err2;
812 }
813 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
814 (int) crypt_ftr.persist_data_size) {
815 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
816 SLOGE("Cannot seek to erase previous persistent data");
817 goto err2;
818 }
819 fsync(fd);
820 memset(pdata, 0, crypt_ftr.persist_data_size);
821 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
822 (int) crypt_ftr.persist_data_size) {
823 SLOGE("Cannot write to erase previous persistent data");
824 goto err2;
825 }
826 fsync(fd);
827 } else {
828 SLOGE("Cannot write to save persistent data");
829 goto err2;
830 }
831
832 /* Success */
833 free(pdata);
834 close(fd);
835 return 0;
836
837err2:
838 free(pdata);
839err:
840 close(fd);
841 return -1;
842}
843
Paul Lawrencef4faa572014-01-29 13:31:03 -0800844static int hexdigit (char c)
845{
846 if (c >= '0' && c <= '9') return c - '0';
847 c = tolower(c);
848 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
849 return -1;
850}
851
852static unsigned char* convert_hex_ascii_to_key(const char* master_key_ascii,
853 unsigned int* out_keysize)
854{
855 unsigned int i;
856 *out_keysize = 0;
857
858 size_t size = strlen (master_key_ascii);
859 if (size % 2) {
860 SLOGE("Trying to convert ascii string of odd length");
861 return NULL;
862 }
863
864 unsigned char* master_key = (unsigned char*) malloc(size / 2);
865 if (master_key == 0) {
866 SLOGE("Cannot allocate");
867 return NULL;
868 }
869
870 for (i = 0; i < size; i += 2) {
871 int high_nibble = hexdigit (master_key_ascii[i]);
872 int low_nibble = hexdigit (master_key_ascii[i + 1]);
873
874 if(high_nibble < 0 || low_nibble < 0) {
875 SLOGE("Invalid hex string");
876 free (master_key);
877 return NULL;
878 }
879
880 master_key[*out_keysize] = high_nibble * 16 + low_nibble;
881 (*out_keysize)++;
882 }
883
884 return master_key;
885}
886
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800887/* Convert a binary key of specified length into an ascii hex string equivalent,
888 * without the leading 0x and with null termination
889 */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800890static void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800891 char *master_key_ascii)
892{
893 unsigned int i, a;
894 unsigned char nibble;
895
896 for (i=0, a=0; i<keysize; i++, a+=2) {
897 /* For each byte, write out two ascii hex digits */
898 nibble = (master_key[i] >> 4) & 0xf;
899 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
900
901 nibble = master_key[i] & 0xf;
902 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
903 }
904
905 /* Add the null termination */
906 master_key_ascii[a] = '\0';
907
908}
909
Ken Sumralldb5e0262013-02-05 17:39:48 -0800910static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
911 char *real_blk_name, const char *name, int fd,
912 char *extra_params)
913{
914 char buffer[DM_CRYPT_BUF_SIZE];
915 struct dm_ioctl *io;
916 struct dm_target_spec *tgt;
917 char *crypt_params;
918 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
919 int i;
920
921 io = (struct dm_ioctl *) buffer;
922
923 /* Load the mapping table for this device */
924 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
925
926 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
927 io->target_count = 1;
928 tgt->status = 0;
929 tgt->sector_start = 0;
930 tgt->length = crypt_ftr->fs_size;
931 strcpy(tgt->target_type, "crypt");
932
933 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
934 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
935 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
936 master_key_ascii, real_blk_name, extra_params);
937 crypt_params += strlen(crypt_params) + 1;
938 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
939 tgt->next = crypt_params - buffer;
940
941 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
942 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
943 break;
944 }
945 usleep(500000);
946 }
947
948 if (i == TABLE_LOAD_RETRIES) {
949 /* We failed to load the table, return an error */
950 return -1;
951 } else {
952 return i + 1;
953 }
954}
955
956
957static int get_dm_crypt_version(int fd, const char *name, int *version)
958{
959 char buffer[DM_CRYPT_BUF_SIZE];
960 struct dm_ioctl *io;
961 struct dm_target_versions *v;
962 int i;
963
964 io = (struct dm_ioctl *) buffer;
965
966 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
967
968 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
969 return -1;
970 }
971
972 /* Iterate over the returned versions, looking for name of "crypt".
973 * When found, get and return the version.
974 */
975 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
976 while (v->next) {
977 if (! strcmp(v->name, "crypt")) {
978 /* We found the crypt driver, return the version, and get out */
979 version[0] = v->version[0];
980 version[1] = v->version[1];
981 version[2] = v->version[2];
982 return 0;
983 }
984 v = (struct dm_target_versions *)(((char *)v) + v->next);
985 }
986
987 return -1;
988}
989
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800990static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -0700991 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800992{
993 char buffer[DM_CRYPT_BUF_SIZE];
994 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
995 char *crypt_params;
996 struct dm_ioctl *io;
997 struct dm_target_spec *tgt;
998 unsigned int minor;
999 int fd;
Ken Sumralle919efe2012-09-29 17:07:41 -07001000 int i;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001001 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001002 int version[3];
1003 char *extra_params;
1004 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001005
1006 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1007 SLOGE("Cannot open device-mapper\n");
1008 goto errout;
1009 }
1010
1011 io = (struct dm_ioctl *) buffer;
1012
1013 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1014 if (ioctl(fd, DM_DEV_CREATE, io)) {
1015 SLOGE("Cannot create dm-crypt device\n");
1016 goto errout;
1017 }
1018
1019 /* Get the device status, in particular, the name of it's device file */
1020 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1021 if (ioctl(fd, DM_DEV_STATUS, io)) {
1022 SLOGE("Cannot retrieve dm-crypt device status\n");
1023 goto errout;
1024 }
1025 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1026 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1027
Ken Sumralldb5e0262013-02-05 17:39:48 -08001028 extra_params = "";
1029 if (! get_dm_crypt_version(fd, name, version)) {
1030 /* Support for allow_discards was added in version 1.11.0 */
1031 if ((version[0] >= 2) ||
1032 ((version[0] == 1) && (version[1] >= 11))) {
1033 extra_params = "1 allow_discards";
1034 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1035 }
Ken Sumralle919efe2012-09-29 17:07:41 -07001036 }
1037
Ken Sumralldb5e0262013-02-05 17:39:48 -08001038 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1039 fd, extra_params);
1040 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001041 SLOGE("Cannot load dm-crypt mapping table.\n");
1042 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001043 } else if (load_count > 1) {
1044 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001045 }
1046
1047 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -08001048 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001049
1050 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1051 SLOGE("Cannot resume the dm-crypt device\n");
1052 goto errout;
1053 }
1054
1055 /* We made it here with no errors. Woot! */
1056 retval = 0;
1057
1058errout:
1059 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1060
1061 return retval;
1062}
1063
Ken Sumrall29d8da82011-05-18 17:20:07 -07001064static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001065{
1066 int fd;
1067 char buffer[DM_CRYPT_BUF_SIZE];
1068 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001069 int retval = -1;
1070
1071 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1072 SLOGE("Cannot open device-mapper\n");
1073 goto errout;
1074 }
1075
1076 io = (struct dm_ioctl *) buffer;
1077
1078 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1079 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1080 SLOGE("Cannot remove dm-crypt device\n");
1081 goto errout;
1082 }
1083
1084 /* We made it here with no errors. Woot! */
1085 retval = 0;
1086
1087errout:
1088 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1089
1090 return retval;
1091
1092}
1093
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001094static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001095 unsigned char *ikey, void *params UNUSED)
1096{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001097 SLOGI("Using pbkdf2 for cryptfs KDF");
1098
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001099 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001100 unsigned int keysize;
1101 char* master_key = (char*)convert_hex_ascii_to_key(passwd, &keysize);
1102 if (!master_key) return -1;
1103 PKCS5_PBKDF2_HMAC_SHA1(master_key, keysize, salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001104 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001105
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001106 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001107 free (master_key);
1108 return 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001109}
1110
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001111static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001112 unsigned char *ikey, void *params)
1113{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001114 SLOGI("Using scrypt for cryptfs KDF");
1115
Kenny Rootc4c70f12013-06-14 12:11:38 -07001116 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1117
1118 int N = 1 << ftr->N_factor;
1119 int r = 1 << ftr->r_factor;
1120 int p = 1 << ftr->p_factor;
1121
1122 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001123 unsigned int keysize;
1124 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &keysize);
1125 if (!master_key) return -1;
1126 crypto_scrypt(master_key, keysize, salt, SALT_LEN, N, r, p, ikey,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001127 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001128
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001129 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001130 free (master_key);
1131 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001132}
1133
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001134static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1135 unsigned char *ikey, void *params)
1136{
1137 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1138
1139 int rc;
1140 unsigned int key_size;
1141 size_t signature_size;
1142 unsigned char* signature;
1143 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1144
1145 int N = 1 << ftr->N_factor;
1146 int r = 1 << ftr->r_factor;
1147 int p = 1 << ftr->p_factor;
1148
1149 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &key_size);
1150 if (!master_key) {
1151 SLOGE("Failed to convert passwd from hex");
1152 return -1;
1153 }
1154
1155 rc = crypto_scrypt(master_key, key_size, salt, SALT_LEN,
1156 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1157 memset(master_key, 0, key_size);
1158 free(master_key);
1159
1160 if (rc) {
1161 SLOGE("scrypt failed");
1162 return -1;
1163 }
1164
1165 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1166 &signature, &signature_size)) {
1167 SLOGE("Signing failed");
1168 return -1;
1169 }
1170
1171 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1172 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1173 free(signature);
1174
1175 if (rc) {
1176 SLOGE("scrypt failed");
1177 return -1;
1178 }
1179
1180 return 0;
1181}
1182
1183static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1184 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001185 unsigned char *encrypted_master_key,
1186 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001187{
1188 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1189 EVP_CIPHER_CTX e_ctx;
1190 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001191 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001192
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001193 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001194 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001195
1196 switch (crypt_ftr->kdf_type) {
1197 case KDF_SCRYPT_KEYMASTER:
1198 if (keymaster_create_key(crypt_ftr)) {
1199 SLOGE("keymaster_create_key failed");
1200 return -1;
1201 }
1202
1203 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1204 SLOGE("scrypt failed");
1205 return -1;
1206 }
1207 break;
1208
1209 case KDF_SCRYPT:
1210 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1211 SLOGE("scrypt failed");
1212 return -1;
1213 }
1214 break;
1215
1216 default:
1217 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001218 return -1;
1219 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001220
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001221 /* Initialize the decryption engine */
1222 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1223 SLOGE("EVP_EncryptInit failed\n");
1224 return -1;
1225 }
1226 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001227
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001228 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001229 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
1230 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001231 SLOGE("EVP_EncryptUpdate failed\n");
1232 return -1;
1233 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001234 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001235 SLOGE("EVP_EncryptFinal failed\n");
1236 return -1;
1237 }
1238
1239 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1240 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1241 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001242 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001243
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001244 /* Store the scrypt of the intermediate key, so we can validate if it's a
1245 password error or mount error when things go wrong.
1246 Note there's no need to check for errors, since if this is incorrect, we
1247 simply won't wipe userdata, which is the correct default behavior
1248 */
1249 int N = 1 << crypt_ftr->N_factor;
1250 int r = 1 << crypt_ftr->r_factor;
1251 int p = 1 << crypt_ftr->p_factor;
1252
1253 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1254 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1255 crypt_ftr->scrypted_intermediate_key,
1256 sizeof(crypt_ftr->scrypted_intermediate_key));
1257
1258 if (rc) {
1259 SLOGE("encrypt_master_key: crypto_scrypt failed");
1260 }
1261
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001262 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001263}
1264
JP Abgrall7bdfa522013-11-15 13:42:56 -08001265static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001266 unsigned char *encrypted_master_key,
1267 unsigned char *decrypted_master_key,
1268 kdf_func kdf, void *kdf_params,
1269 unsigned char** intermediate_key,
1270 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001271{
1272 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 -08001273 EVP_CIPHER_CTX d_ctx;
1274 int decrypted_len, final_len;
1275
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001276 /* Turn the password into an intermediate key and IV that can decrypt the
1277 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001278 if (kdf(passwd, salt, ikey, kdf_params)) {
1279 SLOGE("kdf failed");
1280 return -1;
1281 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001282
1283 /* Initialize the decryption engine */
1284 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1285 return -1;
1286 }
1287 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1288 /* Decrypt the master key */
1289 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1290 encrypted_master_key, KEY_LEN_BYTES)) {
1291 return -1;
1292 }
1293 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1294 return -1;
1295 }
1296
1297 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1298 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001299 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001300
1301 /* Copy intermediate key if needed by params */
1302 if (intermediate_key && intermediate_key_size) {
1303 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1304 if (intermediate_key) {
1305 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1306 *intermediate_key_size = KEY_LEN_BYTES;
1307 }
1308 }
1309
1310 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001311}
1312
Kenny Rootc4c70f12013-06-14 12:11:38 -07001313static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001314{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001315 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1316 *kdf = scrypt_keymaster;
1317 *kdf_params = ftr;
1318 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001319 *kdf = scrypt;
1320 *kdf_params = ftr;
1321 } else {
1322 *kdf = pbkdf2;
1323 *kdf_params = NULL;
1324 }
1325}
1326
JP Abgrall7bdfa522013-11-15 13:42:56 -08001327static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001328 struct crypt_mnt_ftr *crypt_ftr,
1329 unsigned char** intermediate_key,
1330 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001331{
1332 kdf_func kdf;
1333 void *kdf_params;
1334 int ret;
1335
1336 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001337 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1338 decrypted_master_key, kdf, kdf_params,
1339 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001340 if (ret != 0) {
1341 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001342 }
1343
1344 return ret;
1345}
1346
1347static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1348 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001349 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001350 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001351 EVP_CIPHER_CTX e_ctx;
1352 int encrypted_len, final_len;
1353
1354 /* Get some random bits for a key */
1355 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001356 read(fd, key_buf, sizeof(key_buf));
1357 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001358 close(fd);
1359
1360 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001361 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001362}
1363
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001364static int wait_and_unmount(char *mountpoint)
1365{
1366 int i, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001367#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001368
1369 /* Now umount the tmpfs filesystem */
1370 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
1371 if (umount(mountpoint)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001372 if (errno == EINVAL) {
1373 /* EINVAL is returned if the directory is not a mountpoint,
1374 * i.e. there is no filesystem mounted there. So just get out.
1375 */
1376 break;
1377 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001378 sleep(1);
1379 i++;
1380 } else {
1381 break;
1382 }
1383 }
1384
1385 if (i < WAIT_UNMOUNT_COUNT) {
1386 SLOGD("unmounting %s succeeded\n", mountpoint);
1387 rc = 0;
1388 } else {
1389 SLOGE("unmounting %s failed\n", mountpoint);
1390 rc = -1;
1391 }
1392
1393 return rc;
1394}
1395
Ken Sumrallc5872692013-05-14 15:26:31 -07001396#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001397static int prep_data_fs(void)
1398{
1399 int i;
1400
1401 /* Do the prep of the /data filesystem */
1402 property_set("vold.post_fs_data_done", "0");
1403 property_set("vold.decrypt", "trigger_post_fs_data");
1404 SLOGD("Just triggered post_fs_data\n");
1405
Ken Sumrallc5872692013-05-14 15:26:31 -07001406 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001407 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001408 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001409
1410 property_get("vold.post_fs_data_done", p, "0");
1411 if (*p == '1') {
1412 break;
1413 } else {
1414 usleep(250000);
1415 }
1416 }
1417 if (i == DATA_PREP_TIMEOUT) {
1418 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001419 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001420 return -1;
1421 } else {
1422 SLOGD("post_fs_data done\n");
1423 return 0;
1424 }
1425}
1426
Paul Lawrencef4faa572014-01-29 13:31:03 -08001427static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001428{
1429 char fs_type[32];
1430 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001431 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001432 char fs_options[256];
1433 unsigned long mnt_flags;
1434 struct stat statbuf;
1435 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001436 static int restart_successful = 0;
1437
1438 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001439 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001440 SLOGE("Encrypted filesystem not validated, aborting");
1441 return -1;
1442 }
1443
1444 if (restart_successful) {
1445 SLOGE("System already restarted with encrypted disk, aborting");
1446 return -1;
1447 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001448
Paul Lawrencef4faa572014-01-29 13:31:03 -08001449 if (restart_main) {
1450 /* Here is where we shut down the framework. The init scripts
1451 * start all services in one of three classes: core, main or late_start.
1452 * On boot, we start core and main. Now, we stop main, but not core,
1453 * as core includes vold and a few other really important things that
1454 * we need to keep running. Once main has stopped, we should be able
1455 * to umount the tmpfs /data, then mount the encrypted /data.
1456 * We then restart the class main, and also the class late_start.
1457 * At the moment, I've only put a few things in late_start that I know
1458 * are not needed to bring up the framework, and that also cause problems
1459 * with unmounting the tmpfs /data, but I hope to add add more services
1460 * to the late_start class as we optimize this to decrease the delay
1461 * till the user is asked for the password to the filesystem.
1462 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001463
Paul Lawrencef4faa572014-01-29 13:31:03 -08001464 /* The init files are setup to stop the class main when vold.decrypt is
1465 * set to trigger_reset_main.
1466 */
1467 property_set("vold.decrypt", "trigger_reset_main");
1468 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001469
Paul Lawrencef4faa572014-01-29 13:31:03 -08001470 /* Ugh, shutting down the framework is not synchronous, so until it
1471 * can be fixed, this horrible hack will wait a moment for it all to
1472 * shut down before proceeding. Without it, some devices cannot
1473 * restart the graphics services.
1474 */
1475 sleep(2);
1476 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001477
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001478 /* Now that the framework is shutdown, we should be able to umount()
1479 * the tmpfs filesystem, and mount the real one.
1480 */
1481
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001482 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1483 if (strlen(crypto_blkdev) == 0) {
1484 SLOGE("fs_crypto_blkdev not set\n");
1485 return -1;
1486 }
1487
Ken Sumralle5032c42012-04-01 23:58:44 -07001488 if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001489 /* If ro.crypto.readonly is set to 1, mount the decrypted
1490 * filesystem readonly. This is used when /data is mounted by
1491 * recovery mode.
1492 */
1493 char ro_prop[PROPERTY_VALUE_MAX];
1494 property_get("ro.crypto.readonly", ro_prop, "");
1495 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1496 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1497 rec->flags |= MS_RDONLY;
1498 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001499
Ken Sumralle5032c42012-04-01 23:58:44 -07001500 /* If that succeeded, then mount the decrypted filesystem */
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001501 fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001502
Ken Sumralle5032c42012-04-01 23:58:44 -07001503 property_set("vold.decrypt", "trigger_load_persist_props");
1504 /* Create necessary paths on /data */
1505 if (prep_data_fs()) {
1506 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001507 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001508
1509 /* startup service classes main and late_start */
1510 property_set("vold.decrypt", "trigger_restart_framework");
1511 SLOGD("Just triggered restart_framework\n");
1512
1513 /* Give it a few moments to get started */
1514 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001515 }
1516
Ken Sumrall0cc16632011-01-18 20:32:26 -08001517 if (rc == 0) {
1518 restart_successful = 1;
1519 }
1520
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001521 return rc;
1522}
1523
Paul Lawrencef4faa572014-01-29 13:31:03 -08001524int cryptfs_restart(void)
1525{
1526 /* Call internal implementation forcing a restart of main service group */
1527 return cryptfs_restart_internal(1);
1528}
1529
Mark Salyzyn3e971272014-01-21 13:27:04 -08001530static int do_crypto_complete(char *mount_point UNUSED)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001531{
1532 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001533 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001534 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001535
1536 property_get("ro.crypto.state", encrypted_state, "");
1537 if (strcmp(encrypted_state, "encrypted") ) {
1538 SLOGE("not running with encryption, aborting");
1539 return 1;
1540 }
1541
Ken Sumrall160b4d62013-04-22 12:15:39 -07001542 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001543 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001544
Ken Sumralle1a45852011-12-14 21:24:27 -08001545 /*
1546 * Only report this error if key_loc is a file and it exists.
1547 * If the device was never encrypted, and /data is not mountable for
1548 * some reason, returning 1 should prevent the UI from presenting the
1549 * a "enter password" screen, or worse, a "press button to wipe the
1550 * device" screen.
1551 */
1552 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1553 SLOGE("master key file does not exist, aborting");
1554 return 1;
1555 } else {
1556 SLOGE("Error getting crypt footer and key\n");
1557 return -1;
1558 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001559 }
1560
Paul Lawrence6bfed202014-07-28 12:47:22 -07001561 if (crypt_ftr.flags
1562 & (CRYPT_ENCRYPTION_IN_PROGRESS | CRYPT_INCONSISTENT_STATE)) {
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001563 SLOGE("Encryption process didn't finish successfully\n");
1564 return -2; /* -2 is the clue to the UI that there is no usable data on the disk,
1565 * and give the user an option to wipe the disk */
1566 }
1567
1568 /* We passed the test! We shall diminish, and return to the west */
1569 return 0;
1570}
1571
Paul Lawrencef4faa572014-01-29 13:31:03 -08001572static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1573 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001574{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001575 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001576 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001577 char crypto_blkdev[MAXPATHLEN];
1578 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001579 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001580 unsigned int orig_failed_decrypt_count;
1581 int rc;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001582 kdf_func kdf;
1583 void *kdf_params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001584 int use_keymaster = 0;
1585 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001586 unsigned char* intermediate_key = 0;
1587 size_t intermediate_key_size = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001588
Paul Lawrencef4faa572014-01-29 13:31:03 -08001589 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1590 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001591
Paul Lawrencef4faa572014-01-29 13:31:03 -08001592 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001593 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1594 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001595 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001596 rc = -1;
1597 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001598 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001599 }
1600
Paul Lawrencef4faa572014-01-29 13:31:03 -08001601 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1602
1603 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1604 real_blkdev, crypto_blkdev, label)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001605 SLOGE("Error creating decrypted block device\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001606 rc = -1;
1607 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001608 }
1609
Alex Klyubin707795a2013-05-10 15:17:07 -07001610 /* If init detects an encrypted filesystem, it writes a file for each such
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001611 * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
1612 * files and passes that data to me */
1613 /* Create a tmp mount point to try mounting the decryptd fs
1614 * Since we're here, the mount_point should be a tmpfs filesystem, so make
1615 * a directory in it to test mount the decrypted filesystem.
1616 */
1617 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1618 mkdir(tmp_mount_point, 0755);
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001619 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001620 SLOGE("Error temp mounting decrypted block device\n");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001621 delete_crypto_blk_dev(label);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001622
1623 /* Work out if the problem is the password or the data */
1624 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1625 scrypted_intermediate_key)];
1626 int N = 1 << crypt_ftr->N_factor;
1627 int r = 1 << crypt_ftr->r_factor;
1628 int p = 1 << crypt_ftr->p_factor;
1629
1630 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1631 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1632 N, r, p, scrypted_intermediate_key,
1633 sizeof(scrypted_intermediate_key));
1634 if (rc == 0 && memcmp(scrypted_intermediate_key,
1635 crypt_ftr->scrypted_intermediate_key,
1636 sizeof(scrypted_intermediate_key)) == 0) {
1637 SLOGE("Right password, so wipe");
1638 rc = -1;
1639 } else {
1640 SLOGE(rc ? "scrypt failure, so allow retry" :
1641 "Wrong password, so allow retry");
1642 rc = ++crypt_ftr->failed_decrypt_count;
1643 put_crypt_ftr_and_key(crypt_ftr);
1644 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001645 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001646 /* Success!
1647 * umount and we'll mount it properly when we restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001648 */
1649 umount(tmp_mount_point);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001650 crypt_ftr->failed_decrypt_count = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001651
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001652 /* Save the name of the crypto block device
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001653 * so we can mount it when restarting the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001654 */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001655 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001656
1657 /* Also save a the master key so we can reencrypted the key
1658 * the key when we want to change the password on it.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001659 */
Jason parks70a4b3f2011-01-28 10:10:47 -06001660 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001661 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001662 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001663 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001664 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001665
JP Abgrall7bdfa522013-11-15 13:42:56 -08001666 /*
1667 * Upgrade if we're not using the latest KDF.
1668 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001669 use_keymaster = keymaster_check_compatibility();
1670 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1671 // Don't allow downgrade to KDF_SCRYPT
1672 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1673 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1674 upgrade = 1;
1675 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001676 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001677 upgrade = 1;
1678 }
1679
1680 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001681 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1682 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001683 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001684 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001685 }
1686 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1687 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001688 }
1689
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001690 errout:
1691 if (intermediate_key) {
1692 memset(intermediate_key, 0, intermediate_key_size);
1693 free(intermediate_key);
1694 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001695 return rc;
1696}
1697
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001698/* Called by vold when it wants to undo the crypto mapping of a volume it
1699 * manages. This is usually in response to a factory reset, when we want
1700 * to undo the crypto mapping so the volume is formatted in the clear.
1701 */
1702int cryptfs_revert_volume(const char *label)
1703{
1704 return delete_crypto_blk_dev((char *)label);
1705}
1706
Ken Sumrall29d8da82011-05-18 17:20:07 -07001707/*
1708 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1709 * Setup a dm-crypt mapping, use the saved master key from
1710 * setting up the /data mapping, and return the new device path.
1711 */
1712int cryptfs_setup_volume(const char *label, int major, int minor,
1713 char *crypto_sys_path, unsigned int max_path,
1714 int *new_major, int *new_minor)
1715{
1716 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1717 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001718 struct stat statbuf;
1719 int nr_sec, fd;
1720
1721 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1722
Ken Sumrall160b4d62013-04-22 12:15:39 -07001723 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001724
1725 /* Update the fs_size field to be the size of the volume */
1726 fd = open(real_blkdev, O_RDONLY);
1727 nr_sec = get_blkdev_size(fd);
1728 close(fd);
1729 if (nr_sec == 0) {
1730 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1731 return -1;
1732 }
1733
1734 sd_crypt_ftr.fs_size = nr_sec;
1735 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1736 crypto_blkdev, label);
1737
1738 stat(crypto_blkdev, &statbuf);
1739 *new_major = MAJOR(statbuf.st_rdev);
1740 *new_minor = MINOR(statbuf.st_rdev);
1741
1742 /* Create path to sys entry for this block device */
1743 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1744
1745 return 0;
1746}
1747
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001748int cryptfs_crypto_complete(void)
1749{
1750 return do_crypto_complete("/data");
1751}
1752
Paul Lawrencef4faa572014-01-29 13:31:03 -08001753int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1754{
1755 char encrypted_state[PROPERTY_VALUE_MAX];
1756 property_get("ro.crypto.state", encrypted_state, "");
1757 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1758 SLOGE("encrypted fs already validated or not running with encryption,"
1759 " aborting");
1760 return -1;
1761 }
1762
1763 if (get_crypt_ftr_and_key(crypt_ftr)) {
1764 SLOGE("Error getting crypt footer and key");
1765 return -1;
1766 }
1767
1768 return 0;
1769}
1770
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001771int cryptfs_check_passwd(char *passwd)
1772{
Paul Lawrencef4faa572014-01-29 13:31:03 -08001773 struct crypt_mnt_ftr crypt_ftr;
1774 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001775
Paul Lawrencef4faa572014-01-29 13:31:03 -08001776 rc = check_unmounted_and_get_ftr(&crypt_ftr);
1777 if (rc)
1778 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001779
Paul Lawrencef4faa572014-01-29 13:31:03 -08001780 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
1781 DATA_MNT_POINT, "userdata");
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001782
1783 if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001784 cryptfs_clear_password();
1785 password = strdup(passwd);
1786 struct timespec now;
1787 clock_gettime(CLOCK_BOOTTIME, &now);
1788 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001789 }
1790
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001791 return rc;
1792}
1793
Ken Sumrall3ad90722011-10-04 20:38:29 -07001794int cryptfs_verify_passwd(char *passwd)
1795{
1796 struct crypt_mnt_ftr crypt_ftr;
1797 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001798 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001799 char encrypted_state[PROPERTY_VALUE_MAX];
1800 int rc;
1801
1802 property_get("ro.crypto.state", encrypted_state, "");
1803 if (strcmp(encrypted_state, "encrypted") ) {
1804 SLOGE("device not encrypted, aborting");
1805 return -2;
1806 }
1807
1808 if (!master_key_saved) {
1809 SLOGE("encrypted fs not yet mounted, aborting");
1810 return -1;
1811 }
1812
1813 if (!saved_mount_point) {
1814 SLOGE("encrypted fs failed to save mount point, aborting");
1815 return -1;
1816 }
1817
Ken Sumrall160b4d62013-04-22 12:15:39 -07001818 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001819 SLOGE("Error getting crypt footer and key\n");
1820 return -1;
1821 }
1822
1823 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1824 /* If the device has no password, then just say the password is valid */
1825 rc = 0;
1826 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001827 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001828 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1829 /* They match, the password is correct */
1830 rc = 0;
1831 } else {
1832 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1833 sleep(1);
1834 rc = 1;
1835 }
1836 }
1837
1838 return rc;
1839}
1840
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001841/* Initialize a crypt_mnt_ftr structure. The keysize is
1842 * defaulted to 16 bytes, and the filesystem size to 0.
1843 * Presumably, at a minimum, the caller will update the
1844 * filesystem size and crypto_type_name after calling this function.
1845 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001846static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001847{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001848 off64_t off;
1849
1850 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001851 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001852 ftr->major_version = CURRENT_MAJOR_VERSION;
1853 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001854 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001855 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001856
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001857 switch (keymaster_check_compatibility()) {
1858 case 1:
1859 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1860 break;
1861
1862 case 0:
1863 ftr->kdf_type = KDF_SCRYPT;
1864 break;
1865
1866 default:
1867 SLOGE("keymaster_check_compatibility failed");
1868 return -1;
1869 }
1870
Kenny Rootc4c70f12013-06-14 12:11:38 -07001871 get_device_scrypt_params(ftr);
1872
Ken Sumrall160b4d62013-04-22 12:15:39 -07001873 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1874 if (get_crypt_ftr_info(NULL, &off) == 0) {
1875 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1876 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1877 ftr->persist_data_size;
1878 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001879
1880 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001881}
1882
Ken Sumrall29d8da82011-05-18 17:20:07 -07001883static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001884{
Ken Sumralle550f782013-08-20 13:48:23 -07001885 const char *args[10];
1886 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1887 int num_args;
1888 int status;
1889 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001890 int rc = -1;
1891
Ken Sumrall29d8da82011-05-18 17:20:07 -07001892 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001893 args[0] = "/system/bin/make_ext4fs";
1894 args[1] = "-a";
1895 args[2] = "/data";
1896 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07001897 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07001898 args[4] = size_str;
1899 args[5] = crypto_blkdev;
1900 num_args = 6;
1901 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1902 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07001903 } else if (type == F2FS_FS) {
1904 args[0] = "/system/bin/mkfs.f2fs";
1905 args[1] = "-t";
1906 args[2] = "-d1";
1907 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07001908 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07001909 args[4] = size_str;
1910 num_args = 5;
1911 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
1912 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001913 } else {
1914 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1915 return -1;
1916 }
1917
Ken Sumralle550f782013-08-20 13:48:23 -07001918 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1919
1920 if (tmp != 0) {
1921 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001922 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07001923 if (WIFEXITED(status)) {
1924 if (WEXITSTATUS(status)) {
1925 SLOGE("Error creating filesystem on %s, exit status %d ",
1926 crypto_blkdev, WEXITSTATUS(status));
1927 } else {
1928 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
1929 rc = 0;
1930 }
1931 } else {
1932 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
1933 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001934 }
1935
1936 return rc;
1937}
1938
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001939#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08001940#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
1941#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001942
1943/* aligned 32K writes tends to make flash happy.
1944 * SD card association recommends it.
1945 */
1946#define BLOCKS_AT_A_TIME 8
1947
1948struct encryptGroupsData
1949{
1950 int realfd;
1951 int cryptofd;
1952 off64_t numblocks;
1953 off64_t one_pct, cur_pct, new_pct;
1954 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07001955 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001956 char* real_blkdev, * crypto_blkdev;
1957 int count;
1958 off64_t offset;
1959 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08001960 off64_t last_written_sector;
1961 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07001962 time_t time_started;
1963 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001964};
1965
Paul Lawrence58c58cf2014-06-04 13:12:21 -07001966static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001967{
1968 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07001969
1970 if (is_used) {
1971 data->used_blocks_already_done++;
1972 }
Jim Millera70abc62014-08-15 02:00:45 +00001973
Paul Lawrence58c58cf2014-06-04 13:12:21 -07001974 if (data->tot_used_blocks) {
1975 data->new_pct = data->used_blocks_already_done / data->one_pct;
1976 } else {
1977 data->new_pct = data->blocks_already_done / data->one_pct;
1978 }
1979
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001980 if (data->new_pct > data->cur_pct) {
1981 char buf[8];
1982 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07001983 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001984 property_set("vold.encrypt_progress", buf);
Elliott Hughescb33f572014-06-25 18:25:11 -07001985 SLOGI("Encrypted %" PRId64 " percent of drive", data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001986 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07001987
1988 if (data->cur_pct >= 5) {
1989 double elapsed_time = difftime(time(NULL), data->time_started);
1990 off64_t remaining_blocks = data->tot_used_blocks
1991 - data->used_blocks_already_done;
1992 int remaining_time = (int)(elapsed_time * remaining_blocks
1993 / data->used_blocks_already_done);
1994 if (data->remaining_time == -1
1995 || remaining_time < data->remaining_time) {
1996 char buf[8];
1997 snprintf(buf, sizeof(buf), "%d", remaining_time);
1998 property_set("vold.encrypt_time_remaining", buf);
1999
Elliott Hughescb33f572014-06-25 18:25:11 -07002000 SLOGI("Encrypted %" PRId64 " percent of drive, %d seconds to go",
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002001 data->cur_pct, remaining_time);
2002 data->remaining_time = remaining_time;
2003 }
2004 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002005}
2006
2007static int flush_outstanding_data(struct encryptGroupsData* data)
2008{
2009 if (data->count == 0) {
2010 return 0;
2011 }
2012
Elliott Hughes231bdba2014-06-25 18:36:19 -07002013 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002014
2015 if (pread64(data->realfd, data->buffer,
2016 info.block_size * data->count, data->offset)
2017 <= 0) {
2018 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2019 data->real_blkdev);
2020 return -1;
2021 }
2022
2023 if (pwrite64(data->cryptofd, data->buffer,
2024 info.block_size * data->count, data->offset)
2025 <= 0) {
2026 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2027 data->crypto_blkdev);
2028 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002029 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002030 SLOGI("Encrypted %d blocks at sector %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002031 data->count, data->offset / info.block_size * CRYPT_SECTOR_SIZE);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002032 }
2033
2034 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002035 data->last_written_sector = (data->offset + data->count)
2036 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002037 return 0;
2038}
2039
2040static int encrypt_groups(struct encryptGroupsData* data)
2041{
2042 unsigned int i;
2043 u8 *block_bitmap = 0;
2044 unsigned int block;
2045 off64_t ret;
2046 int rc = -1;
2047
2048 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
2049 if (!data->buffer) {
2050 SLOGE("Failed to allocate crypto buffer");
2051 goto errout;
2052 }
2053
2054 block_bitmap = malloc(info.block_size);
2055 if (!block_bitmap) {
2056 SLOGE("failed to allocate block bitmap");
2057 goto errout;
2058 }
2059
2060 for (i = 0; i < aux_info.groups; ++i) {
2061 SLOGI("Encrypting group %d", i);
2062
2063 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2064 u32 block_count = min(info.blocks_per_group,
2065 aux_info.len_blocks - first_block);
2066
2067 off64_t offset = (u64)info.block_size
2068 * aux_info.bg_desc[i].bg_block_bitmap;
2069
2070 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2071 if (ret != (int)info.block_size) {
2072 SLOGE("failed to read all of block group bitmap %d", i);
2073 goto errout;
2074 }
2075
2076 offset = (u64)info.block_size * first_block;
2077
2078 data->count = 0;
2079
2080 for (block = 0; block < block_count; block++) {
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002081 int used = bitmap_get_bit(block_bitmap, block);
2082 update_progress(data, used);
2083 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002084 if (data->count == 0) {
2085 data->offset = offset;
2086 }
2087 data->count++;
2088 } else {
2089 if (flush_outstanding_data(data)) {
2090 goto errout;
2091 }
2092 }
2093
2094 offset += info.block_size;
2095
2096 /* Write data if we are aligned or buffer size reached */
2097 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2098 || data->count == BLOCKS_AT_A_TIME) {
2099 if (flush_outstanding_data(data)) {
2100 goto errout;
2101 }
2102 }
Paul Lawrence87999172014-02-20 12:21:31 -08002103
Paul Lawrence73d7a022014-06-09 14:10:09 -07002104 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002105 SLOGE("Stopping encryption due to low battery");
2106 rc = 0;
2107 goto errout;
2108 }
2109
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002110 }
2111 if (flush_outstanding_data(data)) {
2112 goto errout;
2113 }
2114 }
2115
Paul Lawrence87999172014-02-20 12:21:31 -08002116 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002117 rc = 0;
2118
2119errout:
2120 free(data->buffer);
2121 free(block_bitmap);
2122 return rc;
2123}
2124
2125static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2126 char *real_blkdev,
2127 off64_t size,
2128 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002129 off64_t tot_size,
2130 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002131{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002132 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002133 struct encryptGroupsData data;
2134 int rc = -1;
2135
Paul Lawrence87999172014-02-20 12:21:31 -08002136 if (previously_encrypted_upto > *size_already_done) {
2137 SLOGD("Not fast encrypting since resuming part way through");
2138 return -1;
2139 }
2140
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002141 memset(&data, 0, sizeof(data));
2142 data.real_blkdev = real_blkdev;
2143 data.crypto_blkdev = crypto_blkdev;
2144
2145 if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
2146 SLOGE("Error opening real_blkdev %s for inplace encrypt\n",
2147 real_blkdev);
2148 goto errout;
2149 }
2150
2151 if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
2152 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n",
2153 crypto_blkdev);
2154 goto errout;
2155 }
2156
2157 if (setjmp(setjmp_env)) {
2158 SLOGE("Reading extent caused an exception");
2159 goto errout;
2160 }
2161
2162 if (read_ext(data.realfd, 0) != 0) {
2163 SLOGE("Failed to read extent");
2164 goto errout;
2165 }
2166
2167 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2168 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2169 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2170
2171 SLOGI("Encrypting filesystem in place...");
2172
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002173 data.tot_used_blocks = data.numblocks;
2174 for (i = 0; i < aux_info.groups; ++i) {
2175 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2176 }
2177
2178 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002179 data.cur_pct = 0;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002180 data.time_started = time(NULL);
2181 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002182
2183 rc = encrypt_groups(&data);
2184 if (rc) {
2185 SLOGE("Error encrypting groups");
2186 goto errout;
2187 }
2188
Paul Lawrence87999172014-02-20 12:21:31 -08002189 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002190 rc = 0;
2191
2192errout:
2193 close(data.realfd);
2194 close(data.cryptofd);
2195
2196 return rc;
2197}
2198
2199static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2200 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002201 off64_t tot_size,
2202 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002203{
2204 int realfd, cryptofd;
2205 char *buf[CRYPT_INPLACE_BUFSIZE];
2206 int rc = -1;
2207 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002208 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002209 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002210
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002211 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
2212 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
2213 return -1;
2214 }
2215
2216 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
2217 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
2218 close(realfd);
2219 return -1;
2220 }
2221
2222 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2223 * The size passed in is the number of 512 byte sectors in the filesystem.
2224 * So compute the number of whole 4K blocks we should read/write,
2225 * and the remainder.
2226 */
2227 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2228 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002229 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2230 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002231
2232 SLOGE("Encrypting filesystem in place...");
2233
Paul Lawrence87999172014-02-20 12:21:31 -08002234 i = previously_encrypted_upto + 1 - *size_already_done;
2235
2236 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2237 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2238 goto errout;
2239 }
2240
2241 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2242 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2243 goto errout;
2244 }
2245
2246 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2247 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2248 SLOGE("Error reading initial sectors from real_blkdev %s for "
2249 "inplace encrypt\n", crypto_blkdev);
2250 goto errout;
2251 }
2252 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2253 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2254 "inplace encrypt\n", crypto_blkdev);
2255 goto errout;
2256 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002257 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002258 }
2259 }
2260
Ken Sumrall29d8da82011-05-18 17:20:07 -07002261 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002262 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002263 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002264 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002265 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002266 if (new_pct > cur_pct) {
2267 char buf[8];
2268
2269 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002270 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002271 property_set("vold.encrypt_progress", buf);
2272 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002273 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002274 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002275 goto errout;
2276 }
2277 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002278 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2279 goto errout;
2280 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002281 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002282 CRYPT_SECTORS_PER_BUFSIZE,
2283 i * CRYPT_SECTORS_PER_BUFSIZE);
2284 }
2285
Paul Lawrence73d7a022014-06-09 14:10:09 -07002286 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002287 SLOGE("Stopping encryption due to low battery");
2288 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2289 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002290 goto errout;
2291 }
2292 }
2293
2294 /* Do any remaining sectors */
2295 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002296 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2297 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002298 goto errout;
2299 }
Paul Lawrence87999172014-02-20 12:21:31 -08002300 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2301 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002302 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002303 } else {
2304 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002305 }
2306 }
2307
Ken Sumrall29d8da82011-05-18 17:20:07 -07002308 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002309 rc = 0;
2310
2311errout:
2312 close(realfd);
2313 close(cryptofd);
2314
2315 return rc;
2316}
2317
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002318static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2319 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002320 off64_t tot_size,
2321 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002322{
Paul Lawrence87999172014-02-20 12:21:31 -08002323 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002324 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002325 }
2326
2327 if (*size_already_done + size < previously_encrypted_upto) {
2328 *size_already_done += size;
2329 return 0;
2330 }
2331
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002332 if (cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Jim Millera70abc62014-08-15 02:00:45 +00002333 size, size_already_done,
2334 tot_size, previously_encrypted_upto) == 0) {
2335 return 0;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002336 }
2337
2338 return cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002339 size, size_already_done, tot_size,
2340 previously_encrypted_upto);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002341}
2342
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002343#define CRYPTO_ENABLE_WIPE 1
2344#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002345
2346#define FRAMEWORK_BOOT_WAIT 60
2347
Ken Sumrall29d8da82011-05-18 17:20:07 -07002348static inline int should_encrypt(struct volume_info *volume)
2349{
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002350 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
Ken Sumrall29d8da82011-05-18 17:20:07 -07002351 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
2352}
2353
Paul Lawrence87999172014-02-20 12:21:31 -08002354static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2355{
2356 int fd = open(filename, O_RDONLY);
2357 if (fd == -1) {
2358 SLOGE("Error opening file %s", filename);
2359 return -1;
2360 }
2361
2362 char block[CRYPT_INPLACE_BUFSIZE];
2363 memset(block, 0, sizeof(block));
2364 if (unix_read(fd, block, sizeof(block)) < 0) {
2365 SLOGE("Error reading file %s", filename);
2366 close(fd);
2367 return -1;
2368 }
2369
2370 close(fd);
2371
2372 SHA256_CTX c;
2373 SHA256_Init(&c);
2374 SHA256_Update(&c, block, sizeof(block));
2375 SHA256_Final(buf, &c);
2376
2377 return 0;
2378}
2379
JP Abgrall62c7af32014-06-16 13:01:23 -07002380static int get_fs_type(struct fstab_rec *rec)
2381{
2382 if (!strcmp(rec->fs_type, "ext4")) {
2383 return EXT4_FS;
2384 } else if (!strcmp(rec->fs_type, "f2fs")) {
2385 return F2FS_FS;
2386 } else {
2387 return -1;
2388 }
2389}
2390
Paul Lawrence87999172014-02-20 12:21:31 -08002391static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2392 char *crypto_blkdev, char *real_blkdev,
2393 int previously_encrypted_upto)
2394{
2395 off64_t cur_encryption_done=0, tot_encryption_size=0;
2396 int i, rc = -1;
2397
Paul Lawrence73d7a022014-06-09 14:10:09 -07002398 if (!is_battery_ok_to_start()) {
2399 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002400 return 0;
2401 }
2402
2403 /* The size of the userdata partition, and add in the vold volumes below */
2404 tot_encryption_size = crypt_ftr->fs_size;
2405
2406 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002407 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2408 int fs_type = get_fs_type(rec);
2409 if (fs_type < 0) {
2410 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2411 return -1;
2412 }
2413 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002414 } else if (how == CRYPTO_ENABLE_INPLACE) {
2415 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2416 crypt_ftr->fs_size, &cur_encryption_done,
2417 tot_encryption_size,
2418 previously_encrypted_upto);
2419
Paul Lawrence73d7a022014-06-09 14:10:09 -07002420 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002421 crypt_ftr->encrypted_upto = cur_encryption_done;
2422 }
2423
Paul Lawrence73d7a022014-06-09 14:10:09 -07002424 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002425 /* The inplace routine never actually sets the progress to 100% due
2426 * to the round down nature of integer division, so set it here */
2427 property_set("vold.encrypt_progress", "100");
2428 }
2429 } else {
2430 /* Shouldn't happen */
2431 SLOGE("cryptfs_enable: internal error, unknown option\n");
2432 rc = -1;
2433 }
2434
2435 return rc;
2436}
2437
Paul Lawrence13486032014-02-03 13:28:11 -08002438int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
2439 int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002440{
2441 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002442 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07002443 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002444 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07002445 int rc=-1, fd, i, ret;
Paul Lawrence87999172014-02-20 12:21:31 -08002446 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002447 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002448 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002449 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002450 char key_loc[PROPERTY_VALUE_MAX];
2451 char fuse_sdcard[PROPERTY_VALUE_MAX];
2452 char *sd_mnt_point;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002453 int num_vols;
2454 struct volume_info *vol_list = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002455 off64_t previously_encrypted_upto = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002456
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002457 if (!strcmp(howarg, "wipe")) {
2458 how = CRYPTO_ENABLE_WIPE;
2459 } else if (! strcmp(howarg, "inplace")) {
2460 how = CRYPTO_ENABLE_INPLACE;
2461 } else {
2462 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002463 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002464 }
2465
Paul Lawrence87999172014-02-20 12:21:31 -08002466 /* See if an encryption was underway and interrupted */
2467 if (how == CRYPTO_ENABLE_INPLACE
2468 && get_crypt_ftr_and_key(&crypt_ftr) == 0
2469 && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
2470 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2471 crypt_ftr.encrypted_upto = 0;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002472 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
2473
2474 /* At this point, we are in an inconsistent state. Until we successfully
2475 complete encryption, a reboot will leave us broken. So mark the
2476 encryption failed in case that happens.
2477 On successfully completing encryption, remove this flag */
2478 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2479
2480 put_crypt_ftr_and_key(&crypt_ftr);
Paul Lawrence87999172014-02-20 12:21:31 -08002481 }
2482
2483 property_get("ro.crypto.state", encrypted_state, "");
2484 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2485 SLOGE("Device is already running encrypted, aborting");
2486 goto error_unencrypted;
2487 }
2488
2489 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2490 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002491 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002492
Ken Sumrall3ed82362011-01-28 23:31:16 -08002493 /* Get the size of the real block device */
2494 fd = open(real_blkdev, O_RDONLY);
2495 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
2496 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2497 goto error_unencrypted;
2498 }
2499 close(fd);
2500
2501 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002502 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002503 unsigned int fs_size_sec, max_fs_size_sec;
Daniel Rosenberg74c01202014-08-13 01:56:18 -07002504
Jim Millera70abc62014-08-15 02:00:45 +00002505 fs_size_sec = get_fs_size(real_blkdev);
Paul Lawrence87999172014-02-20 12:21:31 -08002506 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002507
2508 if (fs_size_sec > max_fs_size_sec) {
2509 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2510 goto error_unencrypted;
2511 }
2512 }
2513
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002514 /* Get a wakelock as this may take a while, and we don't want the
2515 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2516 * wants to keep the screen on, it can grab a full wakelock.
2517 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002518 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002519 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2520
Jeff Sharkey7382f812012-08-23 14:08:59 -07002521 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07002522 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07002523 if (!sd_mnt_point) {
2524 sd_mnt_point = getenv("EXTERNAL_STORAGE");
2525 }
2526 if (!sd_mnt_point) {
2527 sd_mnt_point = "/mnt/sdcard";
2528 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07002529
Paul Lawrence87999172014-02-20 12:21:31 -08002530 /* TODO
2531 * Currently do not have test devices with multiple encryptable volumes.
2532 * When we acquire some, re-add support.
2533 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002534 num_vols=vold_getNumDirectVolumes();
2535 vol_list = malloc(sizeof(struct volume_info) * num_vols);
2536 vold_getDirectVolumeList(vol_list);
2537
2538 for (i=0; i<num_vols; i++) {
2539 if (should_encrypt(&vol_list[i])) {
Paul Lawrence87999172014-02-20 12:21:31 -08002540 SLOGE("Cannot encrypt if there are multiple encryptable volumes"
2541 "%s\n", vol_list[i].label);
2542 goto error_unencrypted;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002543 }
2544 }
2545
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002546 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002547 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002548 */
2549 property_set("vold.decrypt", "trigger_shutdown_framework");
2550 SLOGD("Just asked init to shut down class main\n");
2551
Ken Sumrall425524d2012-06-14 20:55:28 -07002552 if (vold_unmountAllAsecs()) {
2553 /* Just report the error. If any are left mounted,
2554 * umounting /data below will fail and handle the error.
2555 */
2556 SLOGE("Error unmounting internal asecs");
2557 }
2558
Ken Sumrall29d8da82011-05-18 17:20:07 -07002559 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
2560 if (!strcmp(fuse_sdcard, "true")) {
2561 /* This is a device using the fuse layer to emulate the sdcard semantics
2562 * on top of the userdata partition. vold does not manage it, it is managed
2563 * by the sdcard service. The sdcard service was killed by the property trigger
2564 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
2565 * unlike the case for vold managed devices above.
2566 */
2567 if (wait_and_unmount(sd_mnt_point)) {
2568 goto error_shutting_down;
2569 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002570 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002571
2572 /* Now unmount the /data partition. */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002573 if (wait_and_unmount(DATA_MNT_POINT)) {
JP Abgrall502dc742013-11-01 13:06:20 -07002574 if (allow_reboot) {
2575 goto error_shutting_down;
2576 } else {
2577 goto error_unencrypted;
2578 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002579 }
2580
2581 /* Do extra work for a better UX when doing the long inplace encryption */
2582 if (how == CRYPTO_ENABLE_INPLACE) {
2583 /* Now that /data is unmounted, we need to mount a tmpfs
2584 * /data, set a property saying we're doing inplace encryption,
2585 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002586 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002587 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002588 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002589 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002590 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002591 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002592
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002593 /* restart the framework. */
2594 /* Create necessary paths on /data */
2595 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002596 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002597 }
2598
Ken Sumrall92736ef2012-10-17 20:57:14 -07002599 /* Ugh, shutting down the framework is not synchronous, so until it
2600 * can be fixed, this horrible hack will wait a moment for it all to
2601 * shut down before proceeding. Without it, some devices cannot
2602 * restart the graphics services.
2603 */
2604 sleep(2);
2605
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002606 /* startup service classes main and late_start */
2607 property_set("vold.decrypt", "trigger_restart_min_framework");
2608 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002609
Ken Sumrall7df84122011-01-18 14:04:08 -08002610 /* OK, the framework is restarted and will soon be showing a
2611 * progress bar. Time to setup an encrypted mapping, and
2612 * either write a new filesystem, or encrypt in place updating
2613 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002614 */
2615 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002616
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002617 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002618 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence87999172014-02-20 12:21:31 -08002619 if (previously_encrypted_upto == 0) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002620 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2621 goto error_shutting_down;
2622 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002623
Paul Lawrence87999172014-02-20 12:21:31 -08002624 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2625 crypt_ftr.fs_size = nr_sec
2626 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2627 } else {
2628 crypt_ftr.fs_size = nr_sec;
2629 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002630 /* At this point, we are in an inconsistent state. Until we successfully
2631 complete encryption, a reboot will leave us broken. So mark the
2632 encryption failed in case that happens.
2633 On successfully completing encryption, remove this flag */
2634 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence87999172014-02-20 12:21:31 -08002635 crypt_ftr.crypt_type = crypt_type;
2636 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002637
Paul Lawrence87999172014-02-20 12:21:31 -08002638 /* Make an encrypted master key */
2639 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
2640 SLOGE("Cannot create encrypted master key\n");
2641 goto error_shutting_down;
2642 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002643
Paul Lawrence87999172014-02-20 12:21:31 -08002644 /* Write the key to the end of the partition */
2645 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002646
Paul Lawrence87999172014-02-20 12:21:31 -08002647 /* If any persistent data has been remembered, save it.
2648 * If none, create a valid empty table and save that.
2649 */
2650 if (!persist_data) {
2651 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
2652 if (pdata) {
2653 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2654 persist_data = pdata;
2655 }
2656 }
2657 if (persist_data) {
2658 save_persistent_data();
2659 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002660 }
2661
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002662 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002663 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
2664 "userdata");
2665
Paul Lawrence87999172014-02-20 12:21:31 -08002666 /* If we are continuing, check checksums match */
2667 rc = 0;
2668 if (previously_encrypted_upto) {
2669 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2670 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002671
Paul Lawrence87999172014-02-20 12:21:31 -08002672 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2673 sizeof(hash_first_block)) != 0) {
2674 SLOGE("Checksums do not match - trigger wipe");
2675 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002676 }
2677 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002678
Paul Lawrence87999172014-02-20 12:21:31 -08002679 if (!rc) {
2680 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
2681 crypto_blkdev, real_blkdev,
2682 previously_encrypted_upto);
2683 }
2684
2685 /* Calculate checksum if we are not finished */
Paul Lawrence73d7a022014-06-09 14:10:09 -07002686 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002687 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2688 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002689 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002690 SLOGE("Error calculating checksum for continuing encryption");
2691 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002692 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002693 }
2694
2695 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002696 delete_crypto_blk_dev("userdata");
Ken Sumrall29d8da82011-05-18 17:20:07 -07002697
2698 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002699
2700 if (! rc) {
2701 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002702 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002703
Paul Lawrence6bfed202014-07-28 12:47:22 -07002704 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002705 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2706 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002707 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002708 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002709
Paul Lawrence6bfed202014-07-28 12:47:22 -07002710 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002711
Ken Sumrall29d8da82011-05-18 17:20:07 -07002712 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08002713 /* Partially encrypted - ensure writes are flushed to ssd */
2714
Paul Lawrence73d7a022014-06-09 14:10:09 -07002715 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002716 cryptfs_reboot(reboot);
2717 } else {
2718 cryptfs_reboot(shutdown);
2719 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002720 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002721 char value[PROPERTY_VALUE_MAX];
2722
Ken Sumrall319369a2012-06-27 16:30:18 -07002723 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002724 if (!strcmp(value, "1")) {
2725 /* wipe data if encryption failed */
2726 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
2727 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07002728 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002729 if (fd >= 0) {
2730 write(fd, "--wipe_data", strlen("--wipe_data") + 1);
2731 close(fd);
2732 } else {
2733 SLOGE("could not open /cache/recovery/command\n");
2734 }
Paul Lawrence87999172014-02-20 12:21:31 -08002735 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002736 } else {
2737 /* set property to trigger dialog */
2738 property_set("vold.encrypt_progress", "error_partially_encrypted");
2739 release_wake_lock(lockid);
2740 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002741 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002742 }
2743
Ken Sumrall3ed82362011-01-28 23:31:16 -08002744 /* hrm, the encrypt step claims success, but the reboot failed.
2745 * This should not happen.
2746 * Set the property and return. Hope the framework can deal with it.
2747 */
2748 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002749 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002750 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002751
2752error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07002753 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002754 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002755 if (lockid[0]) {
2756 release_wake_lock(lockid);
2757 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002758 return -1;
2759
2760error_shutting_down:
2761 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2762 * but the framework is stopped and not restarted to show the error, so it's up to
2763 * vold to restart the system.
2764 */
2765 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08002766 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002767
2768 /* shouldn't get here */
2769 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07002770 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002771 if (lockid[0]) {
2772 release_wake_lock(lockid);
2773 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002774 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002775}
2776
Paul Lawrence45f10532014-04-04 18:11:56 +00002777int cryptfs_enable(char *howarg, int type, char *passwd, int allow_reboot)
Paul Lawrence13486032014-02-03 13:28:11 -08002778{
Paul Lawrence45f10532014-04-04 18:11:56 +00002779 return cryptfs_enable_internal(howarg, type, passwd, allow_reboot);
Paul Lawrence13486032014-02-03 13:28:11 -08002780}
2781
2782int cryptfs_enable_default(char *howarg, int allow_reboot)
2783{
2784 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
2785 DEFAULT_PASSWORD, allow_reboot);
2786}
2787
2788int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002789{
2790 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002791 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002792
2793 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002794 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002795 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002796 return -1;
2797 }
2798
Paul Lawrencef4faa572014-01-29 13:31:03 -08002799 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2800 SLOGE("Invalid crypt_type %d", crypt_type);
2801 return -1;
2802 }
2803
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002804 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002805 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002806 SLOGE("Error getting crypt footer and key");
2807 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002808 }
2809
Paul Lawrencef4faa572014-01-29 13:31:03 -08002810 crypt_ftr.crypt_type = crypt_type;
2811
2812 encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
2813 : newpw,
2814 crypt_ftr.salt,
2815 saved_master_key,
2816 crypt_ftr.master_key,
2817 &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002818
Jason parks70a4b3f2011-01-28 10:10:47 -06002819 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002820 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002821
2822 return 0;
2823}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002824
2825static int persist_get_key(char *fieldname, char *value)
2826{
2827 unsigned int i;
2828
2829 if (persist_data == NULL) {
2830 return -1;
2831 }
2832 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2833 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2834 /* We found it! */
2835 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2836 return 0;
2837 }
2838 }
2839
2840 return -1;
2841}
2842
2843static int persist_set_key(char *fieldname, char *value, int encrypted)
2844{
2845 unsigned int i;
2846 unsigned int num;
2847 struct crypt_mnt_ftr crypt_ftr;
2848 unsigned int max_persistent_entries;
2849 unsigned int dsize;
2850
2851 if (persist_data == NULL) {
2852 return -1;
2853 }
2854
2855 /* If encrypted, use the values from the crypt_ftr, otherwise
2856 * use the values for the current spec.
2857 */
2858 if (encrypted) {
2859 if(get_crypt_ftr_and_key(&crypt_ftr)) {
2860 return -1;
2861 }
2862 dsize = crypt_ftr.persist_data_size;
2863 } else {
2864 dsize = CRYPT_PERSIST_DATA_SIZE;
2865 }
2866 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2867 sizeof(struct crypt_persist_entry);
2868
2869 num = persist_data->persist_valid_entries;
2870
2871 for (i = 0; i < num; i++) {
2872 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2873 /* We found an existing entry, update it! */
2874 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2875 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2876 return 0;
2877 }
2878 }
2879
2880 /* We didn't find it, add it to the end, if there is room */
2881 if (persist_data->persist_valid_entries < max_persistent_entries) {
2882 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2883 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2884 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2885 persist_data->persist_valid_entries++;
2886 return 0;
2887 }
2888
2889 return -1;
2890}
2891
2892/* Return the value of the specified field. */
2893int cryptfs_getfield(char *fieldname, char *value, int len)
2894{
2895 char temp_value[PROPERTY_VALUE_MAX];
2896 char real_blkdev[MAXPATHLEN];
2897 /* 0 is success, 1 is not encrypted,
2898 * -1 is value not set, -2 is any other error
2899 */
2900 int rc = -2;
2901
2902 if (persist_data == NULL) {
2903 load_persistent_data();
2904 if (persist_data == NULL) {
2905 SLOGE("Getfield error, cannot load persistent data");
2906 goto out;
2907 }
2908 }
2909
2910 if (!persist_get_key(fieldname, temp_value)) {
2911 /* We found it, copy it to the caller's buffer and return */
2912 strlcpy(value, temp_value, len);
2913 rc = 0;
2914 } else {
2915 /* Sadness, it's not there. Return the error */
2916 rc = -1;
2917 }
2918
2919out:
2920 return rc;
2921}
2922
2923/* Set the value of the specified field. */
2924int cryptfs_setfield(char *fieldname, char *value)
2925{
2926 struct crypt_persist_data stored_pdata;
2927 struct crypt_persist_data *pdata_p;
2928 struct crypt_mnt_ftr crypt_ftr;
2929 char encrypted_state[PROPERTY_VALUE_MAX];
2930 /* 0 is success, -1 is an error */
2931 int rc = -1;
2932 int encrypted = 0;
2933
2934 if (persist_data == NULL) {
2935 load_persistent_data();
2936 if (persist_data == NULL) {
2937 SLOGE("Setfield error, cannot load persistent data");
2938 goto out;
2939 }
2940 }
2941
2942 property_get("ro.crypto.state", encrypted_state, "");
2943 if (!strcmp(encrypted_state, "encrypted") ) {
2944 encrypted = 1;
2945 }
2946
2947 if (persist_set_key(fieldname, value, encrypted)) {
2948 goto out;
2949 }
2950
2951 /* If we are running encrypted, save the persistent data now */
2952 if (encrypted) {
2953 if (save_persistent_data()) {
2954 SLOGE("Setfield error, cannot save persistent data");
2955 goto out;
2956 }
2957 }
2958
2959 rc = 0;
2960
2961out:
2962 return rc;
2963}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002964
2965/* Checks userdata. Attempt to mount the volume if default-
2966 * encrypted.
2967 * On success trigger next init phase and return 0.
2968 * Currently do not handle failure - see TODO below.
2969 */
2970int cryptfs_mount_default_encrypted(void)
2971{
2972 char decrypt_state[PROPERTY_VALUE_MAX];
2973 property_get("vold.decrypt", decrypt_state, "0");
2974 if (!strcmp(decrypt_state, "0")) {
2975 SLOGE("Not encrypted - should not call here");
2976 } else {
2977 int crypt_type = cryptfs_get_password_type();
2978 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2979 SLOGE("Bad crypt type - error");
2980 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2981 SLOGD("Password is not default - "
2982 "starting min framework to prompt");
2983 property_set("vold.decrypt", "trigger_restart_min_framework");
2984 return 0;
2985 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2986 SLOGD("Password is default - restarting filesystem");
2987 cryptfs_restart_internal(0);
2988 return 0;
2989 } else {
2990 SLOGE("Encrypted, default crypt type but can't decrypt");
2991 }
2992 }
2993
Paul Lawrence6bfed202014-07-28 12:47:22 -07002994 /** Corrupt. Allow us to boot into framework, which will detect bad
2995 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002996 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002997 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002998 return 0;
2999}
3000
3001/* Returns type of the password, default, pattern, pin or password.
3002 */
3003int cryptfs_get_password_type(void)
3004{
3005 struct crypt_mnt_ftr crypt_ftr;
3006
3007 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3008 SLOGE("Error getting crypt footer and key\n");
3009 return -1;
3010 }
3011
Paul Lawrence6bfed202014-07-28 12:47:22 -07003012 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3013 return -1;
3014 }
3015
Paul Lawrencef4faa572014-01-29 13:31:03 -08003016 return crypt_ftr.crypt_type;
3017}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003018
Paul Lawrence399317e2014-03-10 13:20:50 -07003019char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003020{
Paul Lawrence399317e2014-03-10 13:20:50 -07003021 struct timespec now;
3022 clock_gettime(CLOCK_MONOTONIC, &now);
3023 if (now.tv_sec < password_expiry_time) {
3024 return password;
3025 } else {
3026 cryptfs_clear_password();
3027 return 0;
3028 }
3029}
3030
3031void cryptfs_clear_password()
3032{
3033 if (password) {
3034 size_t len = strlen(password);
3035 memset(password, 0, len);
3036 free(password);
3037 password = 0;
3038 password_expiry_time = 0;
3039 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003040}