blob: edde4adccf8e9fd1dde5485d629f5bd8edf02cda [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;
1191
1192 /* Turn the password into a key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001193 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001194
1195 switch (crypt_ftr->kdf_type) {
1196 case KDF_SCRYPT_KEYMASTER:
1197 if (keymaster_create_key(crypt_ftr)) {
1198 SLOGE("keymaster_create_key failed");
1199 return -1;
1200 }
1201
1202 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1203 SLOGE("scrypt failed");
1204 return -1;
1205 }
1206 break;
1207
1208 case KDF_SCRYPT:
1209 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1210 SLOGE("scrypt failed");
1211 return -1;
1212 }
1213 break;
1214
1215 default:
1216 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001217 return -1;
1218 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001219
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001220 /* Initialize the decryption engine */
1221 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1222 SLOGE("EVP_EncryptInit failed\n");
1223 return -1;
1224 }
1225 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001226
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001227 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001228 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
1229 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001230 SLOGE("EVP_EncryptUpdate failed\n");
1231 return -1;
1232 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001233 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001234 SLOGE("EVP_EncryptFinal failed\n");
1235 return -1;
1236 }
1237
1238 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1239 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1240 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001241 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001242
1243 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001244}
1245
JP Abgrall7bdfa522013-11-15 13:42:56 -08001246static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
Ken Sumralle8744072011-01-18 22:01:55 -08001247 unsigned char *encrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001248 unsigned char *decrypted_master_key,
1249 kdf_func kdf, void *kdf_params)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001250{
1251 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 -08001252 EVP_CIPHER_CTX d_ctx;
1253 int decrypted_len, final_len;
1254
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001255 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001256 if (kdf(passwd, salt, ikey, kdf_params)) {
1257 SLOGE("kdf failed");
1258 return -1;
1259 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001260
1261 /* Initialize the decryption engine */
1262 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1263 return -1;
1264 }
1265 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1266 /* Decrypt the master key */
1267 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1268 encrypted_master_key, KEY_LEN_BYTES)) {
1269 return -1;
1270 }
1271 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1272 return -1;
1273 }
1274
1275 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1276 return -1;
1277 } else {
1278 return 0;
1279 }
1280}
1281
Kenny Rootc4c70f12013-06-14 12:11:38 -07001282static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001283{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001284 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1285 *kdf = scrypt_keymaster;
1286 *kdf_params = ftr;
1287 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001288 *kdf = scrypt;
1289 *kdf_params = ftr;
1290 } else {
1291 *kdf = pbkdf2;
1292 *kdf_params = NULL;
1293 }
1294}
1295
JP Abgrall7bdfa522013-11-15 13:42:56 -08001296static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001297 struct crypt_mnt_ftr *crypt_ftr)
1298{
1299 kdf_func kdf;
1300 void *kdf_params;
1301 int ret;
1302
1303 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001304 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, decrypted_master_key, kdf,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001305 kdf_params);
1306 if (ret != 0) {
1307 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001308 }
1309
1310 return ret;
1311}
1312
1313static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1314 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001315 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001316 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001317 EVP_CIPHER_CTX e_ctx;
1318 int encrypted_len, final_len;
1319
1320 /* Get some random bits for a key */
1321 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001322 read(fd, key_buf, sizeof(key_buf));
1323 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001324 close(fd);
1325
1326 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001327 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001328}
1329
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001330static int wait_and_unmount(char *mountpoint)
1331{
1332 int i, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001333#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001334
1335 /* Now umount the tmpfs filesystem */
1336 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
1337 if (umount(mountpoint)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001338 if (errno == EINVAL) {
1339 /* EINVAL is returned if the directory is not a mountpoint,
1340 * i.e. there is no filesystem mounted there. So just get out.
1341 */
1342 break;
1343 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001344 sleep(1);
1345 i++;
1346 } else {
1347 break;
1348 }
1349 }
1350
1351 if (i < WAIT_UNMOUNT_COUNT) {
1352 SLOGD("unmounting %s succeeded\n", mountpoint);
1353 rc = 0;
1354 } else {
1355 SLOGE("unmounting %s failed\n", mountpoint);
1356 rc = -1;
1357 }
1358
1359 return rc;
1360}
1361
Ken Sumrallc5872692013-05-14 15:26:31 -07001362#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001363static int prep_data_fs(void)
1364{
1365 int i;
1366
1367 /* Do the prep of the /data filesystem */
1368 property_set("vold.post_fs_data_done", "0");
1369 property_set("vold.decrypt", "trigger_post_fs_data");
1370 SLOGD("Just triggered post_fs_data\n");
1371
Ken Sumrallc5872692013-05-14 15:26:31 -07001372 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001373 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001374 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001375
1376 property_get("vold.post_fs_data_done", p, "0");
1377 if (*p == '1') {
1378 break;
1379 } else {
1380 usleep(250000);
1381 }
1382 }
1383 if (i == DATA_PREP_TIMEOUT) {
1384 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001385 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001386 return -1;
1387 } else {
1388 SLOGD("post_fs_data done\n");
1389 return 0;
1390 }
1391}
1392
Paul Lawrencef4faa572014-01-29 13:31:03 -08001393static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001394{
1395 char fs_type[32];
1396 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001397 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001398 char fs_options[256];
1399 unsigned long mnt_flags;
1400 struct stat statbuf;
1401 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001402 static int restart_successful = 0;
1403
1404 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001405 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001406 SLOGE("Encrypted filesystem not validated, aborting");
1407 return -1;
1408 }
1409
1410 if (restart_successful) {
1411 SLOGE("System already restarted with encrypted disk, aborting");
1412 return -1;
1413 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001414
Paul Lawrencef4faa572014-01-29 13:31:03 -08001415 if (restart_main) {
1416 /* Here is where we shut down the framework. The init scripts
1417 * start all services in one of three classes: core, main or late_start.
1418 * On boot, we start core and main. Now, we stop main, but not core,
1419 * as core includes vold and a few other really important things that
1420 * we need to keep running. Once main has stopped, we should be able
1421 * to umount the tmpfs /data, then mount the encrypted /data.
1422 * We then restart the class main, and also the class late_start.
1423 * At the moment, I've only put a few things in late_start that I know
1424 * are not needed to bring up the framework, and that also cause problems
1425 * with unmounting the tmpfs /data, but I hope to add add more services
1426 * to the late_start class as we optimize this to decrease the delay
1427 * till the user is asked for the password to the filesystem.
1428 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001429
Paul Lawrencef4faa572014-01-29 13:31:03 -08001430 /* The init files are setup to stop the class main when vold.decrypt is
1431 * set to trigger_reset_main.
1432 */
1433 property_set("vold.decrypt", "trigger_reset_main");
1434 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001435
Paul Lawrencef4faa572014-01-29 13:31:03 -08001436 /* Ugh, shutting down the framework is not synchronous, so until it
1437 * can be fixed, this horrible hack will wait a moment for it all to
1438 * shut down before proceeding. Without it, some devices cannot
1439 * restart the graphics services.
1440 */
1441 sleep(2);
1442 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001443
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001444 /* Now that the framework is shutdown, we should be able to umount()
1445 * the tmpfs filesystem, and mount the real one.
1446 */
1447
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001448 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1449 if (strlen(crypto_blkdev) == 0) {
1450 SLOGE("fs_crypto_blkdev not set\n");
1451 return -1;
1452 }
1453
Ken Sumralle5032c42012-04-01 23:58:44 -07001454 if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001455 /* If ro.crypto.readonly is set to 1, mount the decrypted
1456 * filesystem readonly. This is used when /data is mounted by
1457 * recovery mode.
1458 */
1459 char ro_prop[PROPERTY_VALUE_MAX];
1460 property_get("ro.crypto.readonly", ro_prop, "");
1461 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1462 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1463 rec->flags |= MS_RDONLY;
1464 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001465
Ken Sumralle5032c42012-04-01 23:58:44 -07001466 /* If that succeeded, then mount the decrypted filesystem */
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001467 fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001468
Ken Sumralle5032c42012-04-01 23:58:44 -07001469 property_set("vold.decrypt", "trigger_load_persist_props");
1470 /* Create necessary paths on /data */
1471 if (prep_data_fs()) {
1472 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001473 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001474
1475 /* startup service classes main and late_start */
1476 property_set("vold.decrypt", "trigger_restart_framework");
1477 SLOGD("Just triggered restart_framework\n");
1478
1479 /* Give it a few moments to get started */
1480 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001481 }
1482
Ken Sumrall0cc16632011-01-18 20:32:26 -08001483 if (rc == 0) {
1484 restart_successful = 1;
1485 }
1486
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001487 return rc;
1488}
1489
Paul Lawrencef4faa572014-01-29 13:31:03 -08001490int cryptfs_restart(void)
1491{
1492 /* Call internal implementation forcing a restart of main service group */
1493 return cryptfs_restart_internal(1);
1494}
1495
Mark Salyzyn3e971272014-01-21 13:27:04 -08001496static int do_crypto_complete(char *mount_point UNUSED)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001497{
1498 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001499 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001500 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001501
1502 property_get("ro.crypto.state", encrypted_state, "");
1503 if (strcmp(encrypted_state, "encrypted") ) {
1504 SLOGE("not running with encryption, aborting");
1505 return 1;
1506 }
1507
Ken Sumrall160b4d62013-04-22 12:15:39 -07001508 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001509 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001510
Ken Sumralle1a45852011-12-14 21:24:27 -08001511 /*
1512 * Only report this error if key_loc is a file and it exists.
1513 * If the device was never encrypted, and /data is not mountable for
1514 * some reason, returning 1 should prevent the UI from presenting the
1515 * a "enter password" screen, or worse, a "press button to wipe the
1516 * device" screen.
1517 */
1518 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1519 SLOGE("master key file does not exist, aborting");
1520 return 1;
1521 } else {
1522 SLOGE("Error getting crypt footer and key\n");
1523 return -1;
1524 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001525 }
1526
1527 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1528 SLOGE("Encryption process didn't finish successfully\n");
1529 return -2; /* -2 is the clue to the UI that there is no usable data on the disk,
1530 * and give the user an option to wipe the disk */
1531 }
1532
1533 /* We passed the test! We shall diminish, and return to the west */
1534 return 0;
1535}
1536
Paul Lawrencef4faa572014-01-29 13:31:03 -08001537static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1538 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001539{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001540 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001541 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001542 char crypto_blkdev[MAXPATHLEN];
1543 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001544 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001545 unsigned int orig_failed_decrypt_count;
1546 int rc;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001547 kdf_func kdf;
1548 void *kdf_params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001549 int use_keymaster = 0;
1550 int upgrade = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001551
Paul Lawrencef4faa572014-01-29 13:31:03 -08001552 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1553 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001554
Paul Lawrencef4faa572014-01-29 13:31:03 -08001555 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
1556 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001557 SLOGE("Failed to decrypt master key\n");
1558 return -1;
1559 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001560 }
1561
Paul Lawrencef4faa572014-01-29 13:31:03 -08001562 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1563
1564 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1565 real_blkdev, crypto_blkdev, label)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001566 SLOGE("Error creating decrypted block device\n");
1567 return -1;
1568 }
1569
Alex Klyubin707795a2013-05-10 15:17:07 -07001570 /* If init detects an encrypted filesystem, it writes a file for each such
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001571 * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
1572 * files and passes that data to me */
1573 /* Create a tmp mount point to try mounting the decryptd fs
1574 * Since we're here, the mount_point should be a tmpfs filesystem, so make
1575 * a directory in it to test mount the decrypted filesystem.
1576 */
1577 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1578 mkdir(tmp_mount_point, 0755);
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001579 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001580 SLOGE("Error temp mounting decrypted block device\n");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001581 delete_crypto_blk_dev(label);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001582 crypt_ftr->failed_decrypt_count++;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001583 } else {
1584 /* Success, so just umount and we'll mount it properly when we restart
1585 * the framework.
1586 */
1587 umount(tmp_mount_point);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001588 crypt_ftr->failed_decrypt_count = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001589 }
1590
Paul Lawrencef4faa572014-01-29 13:31:03 -08001591 if (orig_failed_decrypt_count != crypt_ftr->failed_decrypt_count) {
1592 put_crypt_ftr_and_key(crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001593 }
1594
Paul Lawrencef4faa572014-01-29 13:31:03 -08001595 if (crypt_ftr->failed_decrypt_count) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001596 /* We failed to mount the device, so return an error */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001597 rc = crypt_ftr->failed_decrypt_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001598
1599 } else {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001600 /* Woot! Success! Save the name of the crypto block device
1601 * so we can mount it when restarting the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001602 */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001603 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001604
1605 /* Also save a the master key so we can reencrypted the key
1606 * the key when we want to change the password on it.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001607 */
Jason parks70a4b3f2011-01-28 10:10:47 -06001608 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001609 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001610 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001611 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001612 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001613
JP Abgrall7bdfa522013-11-15 13:42:56 -08001614 /*
1615 * Upgrade if we're not using the latest KDF.
1616 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001617 use_keymaster = keymaster_check_compatibility();
1618 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1619 // Don't allow downgrade to KDF_SCRYPT
1620 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1621 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1622 upgrade = 1;
1623 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001624 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001625 upgrade = 1;
1626 }
1627
1628 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001629 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1630 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001631 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001632 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001633 }
1634 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1635 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001636 }
1637
1638 return rc;
1639}
1640
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001641/* Called by vold when it wants to undo the crypto mapping of a volume it
1642 * manages. This is usually in response to a factory reset, when we want
1643 * to undo the crypto mapping so the volume is formatted in the clear.
1644 */
1645int cryptfs_revert_volume(const char *label)
1646{
1647 return delete_crypto_blk_dev((char *)label);
1648}
1649
Ken Sumrall29d8da82011-05-18 17:20:07 -07001650/*
1651 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1652 * Setup a dm-crypt mapping, use the saved master key from
1653 * setting up the /data mapping, and return the new device path.
1654 */
1655int cryptfs_setup_volume(const char *label, int major, int minor,
1656 char *crypto_sys_path, unsigned int max_path,
1657 int *new_major, int *new_minor)
1658{
1659 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1660 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001661 struct stat statbuf;
1662 int nr_sec, fd;
1663
1664 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1665
Ken Sumrall160b4d62013-04-22 12:15:39 -07001666 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001667
1668 /* Update the fs_size field to be the size of the volume */
1669 fd = open(real_blkdev, O_RDONLY);
1670 nr_sec = get_blkdev_size(fd);
1671 close(fd);
1672 if (nr_sec == 0) {
1673 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1674 return -1;
1675 }
1676
1677 sd_crypt_ftr.fs_size = nr_sec;
1678 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1679 crypto_blkdev, label);
1680
1681 stat(crypto_blkdev, &statbuf);
1682 *new_major = MAJOR(statbuf.st_rdev);
1683 *new_minor = MINOR(statbuf.st_rdev);
1684
1685 /* Create path to sys entry for this block device */
1686 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1687
1688 return 0;
1689}
1690
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001691int cryptfs_crypto_complete(void)
1692{
1693 return do_crypto_complete("/data");
1694}
1695
Paul Lawrencef4faa572014-01-29 13:31:03 -08001696int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1697{
1698 char encrypted_state[PROPERTY_VALUE_MAX];
1699 property_get("ro.crypto.state", encrypted_state, "");
1700 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1701 SLOGE("encrypted fs already validated or not running with encryption,"
1702 " aborting");
1703 return -1;
1704 }
1705
1706 if (get_crypt_ftr_and_key(crypt_ftr)) {
1707 SLOGE("Error getting crypt footer and key");
1708 return -1;
1709 }
1710
1711 return 0;
1712}
1713
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001714int cryptfs_check_passwd(char *passwd)
1715{
Paul Lawrencef4faa572014-01-29 13:31:03 -08001716 struct crypt_mnt_ftr crypt_ftr;
1717 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001718
Paul Lawrencef4faa572014-01-29 13:31:03 -08001719 rc = check_unmounted_and_get_ftr(&crypt_ftr);
1720 if (rc)
1721 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001722
Paul Lawrencef4faa572014-01-29 13:31:03 -08001723 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
1724 DATA_MNT_POINT, "userdata");
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001725
1726 if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001727 cryptfs_clear_password();
1728 password = strdup(passwd);
1729 struct timespec now;
1730 clock_gettime(CLOCK_BOOTTIME, &now);
1731 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001732 }
1733
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001734 return rc;
1735}
1736
Ken Sumrall3ad90722011-10-04 20:38:29 -07001737int cryptfs_verify_passwd(char *passwd)
1738{
1739 struct crypt_mnt_ftr crypt_ftr;
1740 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001741 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001742 char encrypted_state[PROPERTY_VALUE_MAX];
1743 int rc;
1744
1745 property_get("ro.crypto.state", encrypted_state, "");
1746 if (strcmp(encrypted_state, "encrypted") ) {
1747 SLOGE("device not encrypted, aborting");
1748 return -2;
1749 }
1750
1751 if (!master_key_saved) {
1752 SLOGE("encrypted fs not yet mounted, aborting");
1753 return -1;
1754 }
1755
1756 if (!saved_mount_point) {
1757 SLOGE("encrypted fs failed to save mount point, aborting");
1758 return -1;
1759 }
1760
Ken Sumrall160b4d62013-04-22 12:15:39 -07001761 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001762 SLOGE("Error getting crypt footer and key\n");
1763 return -1;
1764 }
1765
1766 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1767 /* If the device has no password, then just say the password is valid */
1768 rc = 0;
1769 } else {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001770 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001771 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1772 /* They match, the password is correct */
1773 rc = 0;
1774 } else {
1775 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1776 sleep(1);
1777 rc = 1;
1778 }
1779 }
1780
1781 return rc;
1782}
1783
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001784/* Initialize a crypt_mnt_ftr structure. The keysize is
1785 * defaulted to 16 bytes, and the filesystem size to 0.
1786 * Presumably, at a minimum, the caller will update the
1787 * filesystem size and crypto_type_name after calling this function.
1788 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001789static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001790{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001791 off64_t off;
1792
1793 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001794 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001795 ftr->major_version = CURRENT_MAJOR_VERSION;
1796 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001797 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001798 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001799
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001800 switch (keymaster_check_compatibility()) {
1801 case 1:
1802 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1803 break;
1804
1805 case 0:
1806 ftr->kdf_type = KDF_SCRYPT;
1807 break;
1808
1809 default:
1810 SLOGE("keymaster_check_compatibility failed");
1811 return -1;
1812 }
1813
Kenny Rootc4c70f12013-06-14 12:11:38 -07001814 get_device_scrypt_params(ftr);
1815
Ken Sumrall160b4d62013-04-22 12:15:39 -07001816 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1817 if (get_crypt_ftr_info(NULL, &off) == 0) {
1818 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1819 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1820 ftr->persist_data_size;
1821 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001822
1823 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001824}
1825
Ken Sumrall29d8da82011-05-18 17:20:07 -07001826static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001827{
Ken Sumralle550f782013-08-20 13:48:23 -07001828 const char *args[10];
1829 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1830 int num_args;
1831 int status;
1832 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001833 int rc = -1;
1834
Ken Sumrall29d8da82011-05-18 17:20:07 -07001835 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001836 args[0] = "/system/bin/make_ext4fs";
1837 args[1] = "-a";
1838 args[2] = "/data";
1839 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07001840 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07001841 args[4] = size_str;
1842 args[5] = crypto_blkdev;
1843 num_args = 6;
1844 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1845 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07001846 } else if (type == F2FS_FS) {
1847 args[0] = "/system/bin/mkfs.f2fs";
1848 args[1] = "-t";
1849 args[2] = "-d1";
1850 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07001851 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07001852 args[4] = size_str;
1853 num_args = 5;
1854 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
1855 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001856 } else {
1857 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1858 return -1;
1859 }
1860
Ken Sumralle550f782013-08-20 13:48:23 -07001861 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1862
1863 if (tmp != 0) {
1864 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001865 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07001866 if (WIFEXITED(status)) {
1867 if (WEXITSTATUS(status)) {
1868 SLOGE("Error creating filesystem on %s, exit status %d ",
1869 crypto_blkdev, WEXITSTATUS(status));
1870 } else {
1871 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
1872 rc = 0;
1873 }
1874 } else {
1875 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
1876 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001877 }
1878
1879 return rc;
1880}
1881
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001882#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08001883#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
1884#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001885
1886/* aligned 32K writes tends to make flash happy.
1887 * SD card association recommends it.
1888 */
1889#define BLOCKS_AT_A_TIME 8
1890
1891struct encryptGroupsData
1892{
1893 int realfd;
1894 int cryptofd;
1895 off64_t numblocks;
1896 off64_t one_pct, cur_pct, new_pct;
1897 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07001898 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001899 char* real_blkdev, * crypto_blkdev;
1900 int count;
1901 off64_t offset;
1902 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08001903 off64_t last_written_sector;
1904 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07001905 time_t time_started;
1906 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001907};
1908
Paul Lawrence58c58cf2014-06-04 13:12:21 -07001909static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001910{
1911 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07001912
1913 if (is_used) {
1914 data->used_blocks_already_done++;
1915 }
1916
1917 if (data->tot_used_blocks) {
1918 data->new_pct = data->used_blocks_already_done / data->one_pct;
1919 } else {
1920 data->new_pct = data->blocks_already_done / data->one_pct;
1921 }
1922
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001923 if (data->new_pct > data->cur_pct) {
1924 char buf[8];
1925 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07001926 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001927 property_set("vold.encrypt_progress", buf);
Elliott Hughescb33f572014-06-25 18:25:11 -07001928 SLOGI("Encrypted %" PRId64 " percent of drive", data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001929 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07001930
1931 if (data->cur_pct >= 5) {
1932 double elapsed_time = difftime(time(NULL), data->time_started);
1933 off64_t remaining_blocks = data->tot_used_blocks
1934 - data->used_blocks_already_done;
1935 int remaining_time = (int)(elapsed_time * remaining_blocks
1936 / data->used_blocks_already_done);
1937 if (data->remaining_time == -1
1938 || remaining_time < data->remaining_time) {
1939 char buf[8];
1940 snprintf(buf, sizeof(buf), "%d", remaining_time);
1941 property_set("vold.encrypt_time_remaining", buf);
1942
Elliott Hughescb33f572014-06-25 18:25:11 -07001943 SLOGI("Encrypted %" PRId64 " percent of drive, %d seconds to go",
Paul Lawrencea96d9c92014-06-04 14:05:01 -07001944 data->cur_pct, remaining_time);
1945 data->remaining_time = remaining_time;
1946 }
1947 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001948}
1949
1950static int flush_outstanding_data(struct encryptGroupsData* data)
1951{
1952 if (data->count == 0) {
1953 return 0;
1954 }
1955
Elliott Hughescb33f572014-06-25 18:25:11 -07001956 SLOGV("Copying %d blocks at offset %" PRId64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001957
1958 if (pread64(data->realfd, data->buffer,
1959 info.block_size * data->count, data->offset)
1960 <= 0) {
1961 SLOGE("Error reading real_blkdev %s for inplace encrypt",
1962 data->real_blkdev);
1963 return -1;
1964 }
1965
1966 if (pwrite64(data->cryptofd, data->buffer,
1967 info.block_size * data->count, data->offset)
1968 <= 0) {
1969 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
1970 data->crypto_blkdev);
1971 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08001972 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07001973 SLOGI("Encrypted %d blocks at sector %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08001974 data->count, data->offset / info.block_size * CRYPT_SECTOR_SIZE);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001975 }
1976
1977 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08001978 data->last_written_sector = (data->offset + data->count)
1979 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001980 return 0;
1981}
1982
1983static int encrypt_groups(struct encryptGroupsData* data)
1984{
1985 unsigned int i;
1986 u8 *block_bitmap = 0;
1987 unsigned int block;
1988 off64_t ret;
1989 int rc = -1;
1990
1991 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
1992 if (!data->buffer) {
1993 SLOGE("Failed to allocate crypto buffer");
1994 goto errout;
1995 }
1996
1997 block_bitmap = malloc(info.block_size);
1998 if (!block_bitmap) {
1999 SLOGE("failed to allocate block bitmap");
2000 goto errout;
2001 }
2002
2003 for (i = 0; i < aux_info.groups; ++i) {
2004 SLOGI("Encrypting group %d", i);
2005
2006 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2007 u32 block_count = min(info.blocks_per_group,
2008 aux_info.len_blocks - first_block);
2009
2010 off64_t offset = (u64)info.block_size
2011 * aux_info.bg_desc[i].bg_block_bitmap;
2012
2013 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2014 if (ret != (int)info.block_size) {
2015 SLOGE("failed to read all of block group bitmap %d", i);
2016 goto errout;
2017 }
2018
2019 offset = (u64)info.block_size * first_block;
2020
2021 data->count = 0;
2022
2023 for (block = 0; block < block_count; block++) {
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002024 int used = bitmap_get_bit(block_bitmap, block);
2025 update_progress(data, used);
2026 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002027 if (data->count == 0) {
2028 data->offset = offset;
2029 }
2030 data->count++;
2031 } else {
2032 if (flush_outstanding_data(data)) {
2033 goto errout;
2034 }
2035 }
2036
2037 offset += info.block_size;
2038
2039 /* Write data if we are aligned or buffer size reached */
2040 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2041 || data->count == BLOCKS_AT_A_TIME) {
2042 if (flush_outstanding_data(data)) {
2043 goto errout;
2044 }
2045 }
Paul Lawrence87999172014-02-20 12:21:31 -08002046
Paul Lawrence73d7a022014-06-09 14:10:09 -07002047 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002048 SLOGE("Stopping encryption due to low battery");
2049 rc = 0;
2050 goto errout;
2051 }
2052
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002053 }
2054 if (flush_outstanding_data(data)) {
2055 goto errout;
2056 }
2057 }
2058
Paul Lawrence87999172014-02-20 12:21:31 -08002059 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002060 rc = 0;
2061
2062errout:
2063 free(data->buffer);
2064 free(block_bitmap);
2065 return rc;
2066}
2067
2068static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2069 char *real_blkdev,
2070 off64_t size,
2071 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002072 off64_t tot_size,
2073 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002074{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002075 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002076 struct encryptGroupsData data;
2077 int rc = -1;
2078
Paul Lawrence87999172014-02-20 12:21:31 -08002079 if (previously_encrypted_upto > *size_already_done) {
2080 SLOGD("Not fast encrypting since resuming part way through");
2081 return -1;
2082 }
2083
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002084 memset(&data, 0, sizeof(data));
2085 data.real_blkdev = real_blkdev;
2086 data.crypto_blkdev = crypto_blkdev;
2087
2088 if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
2089 SLOGE("Error opening real_blkdev %s for inplace encrypt\n",
2090 real_blkdev);
2091 goto errout;
2092 }
2093
2094 if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
2095 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n",
2096 crypto_blkdev);
2097 goto errout;
2098 }
2099
2100 if (setjmp(setjmp_env)) {
2101 SLOGE("Reading extent caused an exception");
2102 goto errout;
2103 }
2104
2105 if (read_ext(data.realfd, 0) != 0) {
2106 SLOGE("Failed to read extent");
2107 goto errout;
2108 }
2109
2110 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2111 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2112 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2113
2114 SLOGI("Encrypting filesystem in place...");
2115
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002116 data.tot_used_blocks = data.numblocks;
2117 for (i = 0; i < aux_info.groups; ++i) {
2118 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2119 }
2120
2121 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002122 data.cur_pct = 0;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002123 data.time_started = time(NULL);
2124 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002125
2126 rc = encrypt_groups(&data);
2127 if (rc) {
2128 SLOGE("Error encrypting groups");
2129 goto errout;
2130 }
2131
Paul Lawrence87999172014-02-20 12:21:31 -08002132 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002133 rc = 0;
2134
2135errout:
2136 close(data.realfd);
2137 close(data.cryptofd);
2138
2139 return rc;
2140}
2141
2142static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2143 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002144 off64_t tot_size,
2145 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002146{
2147 int realfd, cryptofd;
2148 char *buf[CRYPT_INPLACE_BUFSIZE];
2149 int rc = -1;
2150 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002151 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002152 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002153
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002154 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
2155 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
2156 return -1;
2157 }
2158
2159 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
2160 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
2161 close(realfd);
2162 return -1;
2163 }
2164
2165 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2166 * The size passed in is the number of 512 byte sectors in the filesystem.
2167 * So compute the number of whole 4K blocks we should read/write,
2168 * and the remainder.
2169 */
2170 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2171 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002172 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2173 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002174
2175 SLOGE("Encrypting filesystem in place...");
2176
Paul Lawrence87999172014-02-20 12:21:31 -08002177 i = previously_encrypted_upto + 1 - *size_already_done;
2178
2179 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2180 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2181 goto errout;
2182 }
2183
2184 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2185 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2186 goto errout;
2187 }
2188
2189 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2190 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2191 SLOGE("Error reading initial sectors from real_blkdev %s for "
2192 "inplace encrypt\n", crypto_blkdev);
2193 goto errout;
2194 }
2195 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2196 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2197 "inplace encrypt\n", crypto_blkdev);
2198 goto errout;
2199 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002200 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002201 }
2202 }
2203
Ken Sumrall29d8da82011-05-18 17:20:07 -07002204 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002205 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002206 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002207 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002208 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002209 if (new_pct > cur_pct) {
2210 char buf[8];
2211
2212 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002213 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002214 property_set("vold.encrypt_progress", buf);
2215 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002216 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002217 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002218 goto errout;
2219 }
2220 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002221 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2222 goto errout;
2223 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002224 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002225 CRYPT_SECTORS_PER_BUFSIZE,
2226 i * CRYPT_SECTORS_PER_BUFSIZE);
2227 }
2228
Paul Lawrence73d7a022014-06-09 14:10:09 -07002229 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002230 SLOGE("Stopping encryption due to low battery");
2231 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2232 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002233 goto errout;
2234 }
2235 }
2236
2237 /* Do any remaining sectors */
2238 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002239 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2240 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002241 goto errout;
2242 }
Paul Lawrence87999172014-02-20 12:21:31 -08002243 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2244 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002245 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002246 } else {
2247 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002248 }
2249 }
2250
Ken Sumrall29d8da82011-05-18 17:20:07 -07002251 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002252 rc = 0;
2253
2254errout:
2255 close(realfd);
2256 close(cryptofd);
2257
2258 return rc;
2259}
2260
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002261static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2262 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002263 off64_t tot_size,
2264 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002265{
Paul Lawrence87999172014-02-20 12:21:31 -08002266 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002267 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002268 }
2269
2270 if (*size_already_done + size < previously_encrypted_upto) {
2271 *size_already_done += size;
2272 return 0;
2273 }
2274
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002275 if (cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002276 size, size_already_done,
2277 tot_size, previously_encrypted_upto) == 0) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002278 return 0;
2279 }
2280
2281 return cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002282 size, size_already_done, tot_size,
2283 previously_encrypted_upto);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002284}
2285
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002286#define CRYPTO_ENABLE_WIPE 1
2287#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002288
2289#define FRAMEWORK_BOOT_WAIT 60
2290
Ken Sumrall29d8da82011-05-18 17:20:07 -07002291static inline int should_encrypt(struct volume_info *volume)
2292{
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002293 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
Ken Sumrall29d8da82011-05-18 17:20:07 -07002294 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
2295}
2296
Paul Lawrence87999172014-02-20 12:21:31 -08002297static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2298{
2299 int fd = open(filename, O_RDONLY);
2300 if (fd == -1) {
2301 SLOGE("Error opening file %s", filename);
2302 return -1;
2303 }
2304
2305 char block[CRYPT_INPLACE_BUFSIZE];
2306 memset(block, 0, sizeof(block));
2307 if (unix_read(fd, block, sizeof(block)) < 0) {
2308 SLOGE("Error reading file %s", filename);
2309 close(fd);
2310 return -1;
2311 }
2312
2313 close(fd);
2314
2315 SHA256_CTX c;
2316 SHA256_Init(&c);
2317 SHA256_Update(&c, block, sizeof(block));
2318 SHA256_Final(buf, &c);
2319
2320 return 0;
2321}
2322
JP Abgrall62c7af32014-06-16 13:01:23 -07002323static int get_fs_type(struct fstab_rec *rec)
2324{
2325 if (!strcmp(rec->fs_type, "ext4")) {
2326 return EXT4_FS;
2327 } else if (!strcmp(rec->fs_type, "f2fs")) {
2328 return F2FS_FS;
2329 } else {
2330 return -1;
2331 }
2332}
2333
Paul Lawrence87999172014-02-20 12:21:31 -08002334static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2335 char *crypto_blkdev, char *real_blkdev,
2336 int previously_encrypted_upto)
2337{
2338 off64_t cur_encryption_done=0, tot_encryption_size=0;
2339 int i, rc = -1;
2340
Paul Lawrence73d7a022014-06-09 14:10:09 -07002341 if (!is_battery_ok_to_start()) {
2342 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002343 return 0;
2344 }
2345
2346 /* The size of the userdata partition, and add in the vold volumes below */
2347 tot_encryption_size = crypt_ftr->fs_size;
2348
2349 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002350 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2351 int fs_type = get_fs_type(rec);
2352 if (fs_type < 0) {
2353 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2354 return -1;
2355 }
2356 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002357 } else if (how == CRYPTO_ENABLE_INPLACE) {
2358 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2359 crypt_ftr->fs_size, &cur_encryption_done,
2360 tot_encryption_size,
2361 previously_encrypted_upto);
2362
Paul Lawrence73d7a022014-06-09 14:10:09 -07002363 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002364 crypt_ftr->encrypted_upto = cur_encryption_done;
2365 }
2366
Paul Lawrence73d7a022014-06-09 14:10:09 -07002367 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002368 /* The inplace routine never actually sets the progress to 100% due
2369 * to the round down nature of integer division, so set it here */
2370 property_set("vold.encrypt_progress", "100");
2371 }
2372 } else {
2373 /* Shouldn't happen */
2374 SLOGE("cryptfs_enable: internal error, unknown option\n");
2375 rc = -1;
2376 }
2377
2378 return rc;
2379}
2380
Paul Lawrence13486032014-02-03 13:28:11 -08002381int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
2382 int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002383{
2384 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002385 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07002386 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002387 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07002388 int rc=-1, fd, i, ret;
Paul Lawrence87999172014-02-20 12:21:31 -08002389 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002390 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002391 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002392 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002393 char key_loc[PROPERTY_VALUE_MAX];
2394 char fuse_sdcard[PROPERTY_VALUE_MAX];
2395 char *sd_mnt_point;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002396 int num_vols;
2397 struct volume_info *vol_list = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002398 off64_t previously_encrypted_upto = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002399
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002400 if (!strcmp(howarg, "wipe")) {
2401 how = CRYPTO_ENABLE_WIPE;
2402 } else if (! strcmp(howarg, "inplace")) {
2403 how = CRYPTO_ENABLE_INPLACE;
2404 } else {
2405 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002406 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002407 }
2408
Paul Lawrence87999172014-02-20 12:21:31 -08002409 /* See if an encryption was underway and interrupted */
2410 if (how == CRYPTO_ENABLE_INPLACE
2411 && get_crypt_ftr_and_key(&crypt_ftr) == 0
2412 && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
2413 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2414 crypt_ftr.encrypted_upto = 0;
2415 }
2416
2417 property_get("ro.crypto.state", encrypted_state, "");
2418 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2419 SLOGE("Device is already running encrypted, aborting");
2420 goto error_unencrypted;
2421 }
2422
2423 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2424 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002425 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002426
Ken Sumrall3ed82362011-01-28 23:31:16 -08002427 /* Get the size of the real block device */
2428 fd = open(real_blkdev, O_RDONLY);
2429 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
2430 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2431 goto error_unencrypted;
2432 }
2433 close(fd);
2434
2435 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002436 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002437 unsigned int fs_size_sec, max_fs_size_sec;
2438
2439 fs_size_sec = get_fs_size(real_blkdev);
Paul Lawrence87999172014-02-20 12:21:31 -08002440 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002441
2442 if (fs_size_sec > max_fs_size_sec) {
2443 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2444 goto error_unencrypted;
2445 }
2446 }
2447
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002448 /* Get a wakelock as this may take a while, and we don't want the
2449 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2450 * wants to keep the screen on, it can grab a full wakelock.
2451 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002452 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002453 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2454
Jeff Sharkey7382f812012-08-23 14:08:59 -07002455 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07002456 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07002457 if (!sd_mnt_point) {
2458 sd_mnt_point = getenv("EXTERNAL_STORAGE");
2459 }
2460 if (!sd_mnt_point) {
2461 sd_mnt_point = "/mnt/sdcard";
2462 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07002463
Paul Lawrence87999172014-02-20 12:21:31 -08002464 /* TODO
2465 * Currently do not have test devices with multiple encryptable volumes.
2466 * When we acquire some, re-add support.
2467 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002468 num_vols=vold_getNumDirectVolumes();
2469 vol_list = malloc(sizeof(struct volume_info) * num_vols);
2470 vold_getDirectVolumeList(vol_list);
2471
2472 for (i=0; i<num_vols; i++) {
2473 if (should_encrypt(&vol_list[i])) {
Paul Lawrence87999172014-02-20 12:21:31 -08002474 SLOGE("Cannot encrypt if there are multiple encryptable volumes"
2475 "%s\n", vol_list[i].label);
2476 goto error_unencrypted;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002477 }
2478 }
2479
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002480 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002481 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002482 */
2483 property_set("vold.decrypt", "trigger_shutdown_framework");
2484 SLOGD("Just asked init to shut down class main\n");
2485
Ken Sumrall425524d2012-06-14 20:55:28 -07002486 if (vold_unmountAllAsecs()) {
2487 /* Just report the error. If any are left mounted,
2488 * umounting /data below will fail and handle the error.
2489 */
2490 SLOGE("Error unmounting internal asecs");
2491 }
2492
Ken Sumrall29d8da82011-05-18 17:20:07 -07002493 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
2494 if (!strcmp(fuse_sdcard, "true")) {
2495 /* This is a device using the fuse layer to emulate the sdcard semantics
2496 * on top of the userdata partition. vold does not manage it, it is managed
2497 * by the sdcard service. The sdcard service was killed by the property trigger
2498 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
2499 * unlike the case for vold managed devices above.
2500 */
2501 if (wait_and_unmount(sd_mnt_point)) {
2502 goto error_shutting_down;
2503 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002504 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002505
2506 /* Now unmount the /data partition. */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002507 if (wait_and_unmount(DATA_MNT_POINT)) {
JP Abgrall502dc742013-11-01 13:06:20 -07002508 if (allow_reboot) {
2509 goto error_shutting_down;
2510 } else {
2511 goto error_unencrypted;
2512 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002513 }
2514
2515 /* Do extra work for a better UX when doing the long inplace encryption */
2516 if (how == CRYPTO_ENABLE_INPLACE) {
2517 /* Now that /data is unmounted, we need to mount a tmpfs
2518 * /data, set a property saying we're doing inplace encryption,
2519 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002520 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002521 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002522 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002523 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002524 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002525 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002526
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002527 /* restart the framework. */
2528 /* Create necessary paths on /data */
2529 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002530 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002531 }
2532
Ken Sumrall92736ef2012-10-17 20:57:14 -07002533 /* Ugh, shutting down the framework is not synchronous, so until it
2534 * can be fixed, this horrible hack will wait a moment for it all to
2535 * shut down before proceeding. Without it, some devices cannot
2536 * restart the graphics services.
2537 */
2538 sleep(2);
2539
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002540 /* startup service classes main and late_start */
2541 property_set("vold.decrypt", "trigger_restart_min_framework");
2542 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002543
Ken Sumrall7df84122011-01-18 14:04:08 -08002544 /* OK, the framework is restarted and will soon be showing a
2545 * progress bar. Time to setup an encrypted mapping, and
2546 * either write a new filesystem, or encrypt in place updating
2547 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002548 */
2549 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002550
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002551 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002552 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence87999172014-02-20 12:21:31 -08002553 if (previously_encrypted_upto == 0) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002554 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2555 goto error_shutting_down;
2556 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002557
Paul Lawrence87999172014-02-20 12:21:31 -08002558 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2559 crypt_ftr.fs_size = nr_sec
2560 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2561 } else {
2562 crypt_ftr.fs_size = nr_sec;
2563 }
2564 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
2565 crypt_ftr.crypt_type = crypt_type;
2566 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002567
Paul Lawrence87999172014-02-20 12:21:31 -08002568 /* Make an encrypted master key */
2569 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
2570 SLOGE("Cannot create encrypted master key\n");
2571 goto error_shutting_down;
2572 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002573
Paul Lawrence87999172014-02-20 12:21:31 -08002574 /* Write the key to the end of the partition */
2575 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002576
Paul Lawrence87999172014-02-20 12:21:31 -08002577 /* If any persistent data has been remembered, save it.
2578 * If none, create a valid empty table and save that.
2579 */
2580 if (!persist_data) {
2581 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
2582 if (pdata) {
2583 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2584 persist_data = pdata;
2585 }
2586 }
2587 if (persist_data) {
2588 save_persistent_data();
2589 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002590 }
2591
JP Abgrall7bdfa522013-11-15 13:42:56 -08002592 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002593 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
2594 "userdata");
2595
Paul Lawrence87999172014-02-20 12:21:31 -08002596 /* If we are continuing, check checksums match */
2597 rc = 0;
2598 if (previously_encrypted_upto) {
2599 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2600 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002601
Paul Lawrence87999172014-02-20 12:21:31 -08002602 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2603 sizeof(hash_first_block)) != 0) {
2604 SLOGE("Checksums do not match - trigger wipe");
2605 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002606 }
2607 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002608
Paul Lawrence87999172014-02-20 12:21:31 -08002609 if (!rc) {
2610 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
2611 crypto_blkdev, real_blkdev,
2612 previously_encrypted_upto);
2613 }
2614
2615 /* Calculate checksum if we are not finished */
Paul Lawrence73d7a022014-06-09 14:10:09 -07002616 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002617 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2618 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002619 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002620 SLOGE("Error calculating checksum for continuing encryption");
2621 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002622 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002623 }
2624
2625 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002626 delete_crypto_blk_dev("userdata");
Ken Sumrall29d8da82011-05-18 17:20:07 -07002627
2628 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002629
2630 if (! rc) {
2631 /* Success */
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002632
Paul Lawrence73d7a022014-06-09 14:10:09 -07002633 /* Clear the encryption in progress flag in the footer */
2634 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002635 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
2636 } else {
2637 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2638 crypt_ftr.encrypted_upto);
2639 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002640
2641 if (crypt_ftr.encrypted_upto) {
2642 put_crypt_ftr_and_key(&crypt_ftr);
2643 }
Ken Sumralld33d4172011-02-01 00:49:13 -08002644
Ken Sumrall29d8da82011-05-18 17:20:07 -07002645 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08002646 /* Partially encrypted - ensure writes are flushed to ssd */
2647
Paul Lawrence73d7a022014-06-09 14:10:09 -07002648 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002649 cryptfs_reboot(reboot);
2650 } else {
2651 cryptfs_reboot(shutdown);
2652 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002653 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002654 char value[PROPERTY_VALUE_MAX];
2655
Ken Sumrall319369a2012-06-27 16:30:18 -07002656 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002657 if (!strcmp(value, "1")) {
2658 /* wipe data if encryption failed */
2659 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
2660 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07002661 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002662 if (fd >= 0) {
2663 write(fd, "--wipe_data", strlen("--wipe_data") + 1);
2664 close(fd);
2665 } else {
2666 SLOGE("could not open /cache/recovery/command\n");
2667 }
Paul Lawrence87999172014-02-20 12:21:31 -08002668 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002669 } else {
2670 /* set property to trigger dialog */
2671 property_set("vold.encrypt_progress", "error_partially_encrypted");
2672 release_wake_lock(lockid);
2673 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002674 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002675 }
2676
Ken Sumrall3ed82362011-01-28 23:31:16 -08002677 /* hrm, the encrypt step claims success, but the reboot failed.
2678 * This should not happen.
2679 * Set the property and return. Hope the framework can deal with it.
2680 */
2681 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002682 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002683 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002684
2685error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07002686 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002687 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002688 if (lockid[0]) {
2689 release_wake_lock(lockid);
2690 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002691 return -1;
2692
2693error_shutting_down:
2694 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2695 * but the framework is stopped and not restarted to show the error, so it's up to
2696 * vold to restart the system.
2697 */
2698 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08002699 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002700
2701 /* shouldn't get here */
2702 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07002703 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002704 if (lockid[0]) {
2705 release_wake_lock(lockid);
2706 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002707 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002708}
2709
Paul Lawrence45f10532014-04-04 18:11:56 +00002710int cryptfs_enable(char *howarg, int type, char *passwd, int allow_reboot)
Paul Lawrence13486032014-02-03 13:28:11 -08002711{
Paul Lawrence45f10532014-04-04 18:11:56 +00002712 return cryptfs_enable_internal(howarg, type, passwd, allow_reboot);
Paul Lawrence13486032014-02-03 13:28:11 -08002713}
2714
2715int cryptfs_enable_default(char *howarg, int allow_reboot)
2716{
2717 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
2718 DEFAULT_PASSWORD, allow_reboot);
2719}
2720
2721int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002722{
2723 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002724 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002725
2726 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002727 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002728 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002729 return -1;
2730 }
2731
Paul Lawrencef4faa572014-01-29 13:31:03 -08002732 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2733 SLOGE("Invalid crypt_type %d", crypt_type);
2734 return -1;
2735 }
2736
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002737 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002738 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002739 SLOGE("Error getting crypt footer and key");
2740 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002741 }
2742
Paul Lawrencef4faa572014-01-29 13:31:03 -08002743 crypt_ftr.crypt_type = crypt_type;
2744
2745 encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
2746 : newpw,
2747 crypt_ftr.salt,
2748 saved_master_key,
2749 crypt_ftr.master_key,
2750 &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002751
Jason parks70a4b3f2011-01-28 10:10:47 -06002752 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002753 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002754
2755 return 0;
2756}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002757
2758static int persist_get_key(char *fieldname, char *value)
2759{
2760 unsigned int i;
2761
2762 if (persist_data == NULL) {
2763 return -1;
2764 }
2765 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2766 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2767 /* We found it! */
2768 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2769 return 0;
2770 }
2771 }
2772
2773 return -1;
2774}
2775
2776static int persist_set_key(char *fieldname, char *value, int encrypted)
2777{
2778 unsigned int i;
2779 unsigned int num;
2780 struct crypt_mnt_ftr crypt_ftr;
2781 unsigned int max_persistent_entries;
2782 unsigned int dsize;
2783
2784 if (persist_data == NULL) {
2785 return -1;
2786 }
2787
2788 /* If encrypted, use the values from the crypt_ftr, otherwise
2789 * use the values for the current spec.
2790 */
2791 if (encrypted) {
2792 if(get_crypt_ftr_and_key(&crypt_ftr)) {
2793 return -1;
2794 }
2795 dsize = crypt_ftr.persist_data_size;
2796 } else {
2797 dsize = CRYPT_PERSIST_DATA_SIZE;
2798 }
2799 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2800 sizeof(struct crypt_persist_entry);
2801
2802 num = persist_data->persist_valid_entries;
2803
2804 for (i = 0; i < num; i++) {
2805 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2806 /* We found an existing entry, update it! */
2807 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2808 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2809 return 0;
2810 }
2811 }
2812
2813 /* We didn't find it, add it to the end, if there is room */
2814 if (persist_data->persist_valid_entries < max_persistent_entries) {
2815 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2816 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2817 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2818 persist_data->persist_valid_entries++;
2819 return 0;
2820 }
2821
2822 return -1;
2823}
2824
2825/* Return the value of the specified field. */
2826int cryptfs_getfield(char *fieldname, char *value, int len)
2827{
2828 char temp_value[PROPERTY_VALUE_MAX];
2829 char real_blkdev[MAXPATHLEN];
2830 /* 0 is success, 1 is not encrypted,
2831 * -1 is value not set, -2 is any other error
2832 */
2833 int rc = -2;
2834
2835 if (persist_data == NULL) {
2836 load_persistent_data();
2837 if (persist_data == NULL) {
2838 SLOGE("Getfield error, cannot load persistent data");
2839 goto out;
2840 }
2841 }
2842
2843 if (!persist_get_key(fieldname, temp_value)) {
2844 /* We found it, copy it to the caller's buffer and return */
2845 strlcpy(value, temp_value, len);
2846 rc = 0;
2847 } else {
2848 /* Sadness, it's not there. Return the error */
2849 rc = -1;
2850 }
2851
2852out:
2853 return rc;
2854}
2855
2856/* Set the value of the specified field. */
2857int cryptfs_setfield(char *fieldname, char *value)
2858{
2859 struct crypt_persist_data stored_pdata;
2860 struct crypt_persist_data *pdata_p;
2861 struct crypt_mnt_ftr crypt_ftr;
2862 char encrypted_state[PROPERTY_VALUE_MAX];
2863 /* 0 is success, -1 is an error */
2864 int rc = -1;
2865 int encrypted = 0;
2866
2867 if (persist_data == NULL) {
2868 load_persistent_data();
2869 if (persist_data == NULL) {
2870 SLOGE("Setfield error, cannot load persistent data");
2871 goto out;
2872 }
2873 }
2874
2875 property_get("ro.crypto.state", encrypted_state, "");
2876 if (!strcmp(encrypted_state, "encrypted") ) {
2877 encrypted = 1;
2878 }
2879
2880 if (persist_set_key(fieldname, value, encrypted)) {
2881 goto out;
2882 }
2883
2884 /* If we are running encrypted, save the persistent data now */
2885 if (encrypted) {
2886 if (save_persistent_data()) {
2887 SLOGE("Setfield error, cannot save persistent data");
2888 goto out;
2889 }
2890 }
2891
2892 rc = 0;
2893
2894out:
2895 return rc;
2896}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002897
2898/* Checks userdata. Attempt to mount the volume if default-
2899 * encrypted.
2900 * On success trigger next init phase and return 0.
2901 * Currently do not handle failure - see TODO below.
2902 */
2903int cryptfs_mount_default_encrypted(void)
2904{
2905 char decrypt_state[PROPERTY_VALUE_MAX];
2906 property_get("vold.decrypt", decrypt_state, "0");
2907 if (!strcmp(decrypt_state, "0")) {
2908 SLOGE("Not encrypted - should not call here");
2909 } else {
2910 int crypt_type = cryptfs_get_password_type();
2911 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2912 SLOGE("Bad crypt type - error");
2913 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2914 SLOGD("Password is not default - "
2915 "starting min framework to prompt");
2916 property_set("vold.decrypt", "trigger_restart_min_framework");
2917 return 0;
2918 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2919 SLOGD("Password is default - restarting filesystem");
2920 cryptfs_restart_internal(0);
2921 return 0;
2922 } else {
2923 SLOGE("Encrypted, default crypt type but can't decrypt");
2924 }
2925 }
2926
2927 /** @TODO make sure we factory wipe in this situation
2928 * In general if we got here there is no recovery
2929 */
2930 return 0;
2931}
2932
2933/* Returns type of the password, default, pattern, pin or password.
2934 */
2935int cryptfs_get_password_type(void)
2936{
2937 struct crypt_mnt_ftr crypt_ftr;
2938
2939 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2940 SLOGE("Error getting crypt footer and key\n");
2941 return -1;
2942 }
2943
2944 return crypt_ftr.crypt_type;
2945}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002946
Paul Lawrence399317e2014-03-10 13:20:50 -07002947char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002948{
Paul Lawrence399317e2014-03-10 13:20:50 -07002949 struct timespec now;
2950 clock_gettime(CLOCK_MONOTONIC, &now);
2951 if (now.tv_sec < password_expiry_time) {
2952 return password;
2953 } else {
2954 cryptfs_clear_password();
2955 return 0;
2956 }
2957}
2958
2959void cryptfs_clear_password()
2960{
2961 if (password) {
2962 size_t len = strlen(password);
2963 memset(password, 0, len);
2964 free(password);
2965 password = 0;
2966 password_expiry_time = 0;
2967 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002968}