blob: 252be0a2da2de1db9d82404a5f4d88fc607f5024 [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
Paul Lawrence6bfed202014-07-28 12:47:22 -07001527 if (crypt_ftr.flags
1528 & (CRYPT_ENCRYPTION_IN_PROGRESS | CRYPT_INCONSISTENT_STATE)) {
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001529 SLOGE("Encryption process didn't finish successfully\n");
1530 return -2; /* -2 is the clue to the UI that there is no usable data on the disk,
1531 * and give the user an option to wipe the disk */
1532 }
1533
1534 /* We passed the test! We shall diminish, and return to the west */
1535 return 0;
1536}
1537
Paul Lawrencef4faa572014-01-29 13:31:03 -08001538static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1539 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001540{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001541 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001542 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001543 char crypto_blkdev[MAXPATHLEN];
1544 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001545 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001546 unsigned int orig_failed_decrypt_count;
1547 int rc;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001548 kdf_func kdf;
1549 void *kdf_params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001550 int use_keymaster = 0;
1551 int upgrade = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001552
Paul Lawrencef4faa572014-01-29 13:31:03 -08001553 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1554 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001555
Paul Lawrencef4faa572014-01-29 13:31:03 -08001556 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
1557 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001558 SLOGE("Failed to decrypt master key\n");
1559 return -1;
1560 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001561 }
1562
Paul Lawrencef4faa572014-01-29 13:31:03 -08001563 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1564
1565 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1566 real_blkdev, crypto_blkdev, label)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001567 SLOGE("Error creating decrypted block device\n");
1568 return -1;
1569 }
1570
Alex Klyubin707795a2013-05-10 15:17:07 -07001571 /* If init detects an encrypted filesystem, it writes a file for each such
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001572 * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
1573 * files and passes that data to me */
1574 /* Create a tmp mount point to try mounting the decryptd fs
1575 * Since we're here, the mount_point should be a tmpfs filesystem, so make
1576 * a directory in it to test mount the decrypted filesystem.
1577 */
1578 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1579 mkdir(tmp_mount_point, 0755);
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001580 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001581 SLOGE("Error temp mounting decrypted block device\n");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001582 delete_crypto_blk_dev(label);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001583 crypt_ftr->failed_decrypt_count++;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001584 } else {
1585 /* Success, so just umount and we'll mount it properly when we restart
1586 * the framework.
1587 */
1588 umount(tmp_mount_point);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001589 crypt_ftr->failed_decrypt_count = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001590 }
1591
Paul Lawrencef4faa572014-01-29 13:31:03 -08001592 if (orig_failed_decrypt_count != crypt_ftr->failed_decrypt_count) {
1593 put_crypt_ftr_and_key(crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001594 }
1595
Paul Lawrencef4faa572014-01-29 13:31:03 -08001596 if (crypt_ftr->failed_decrypt_count) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001597 /* We failed to mount the device, so return an error */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001598 rc = crypt_ftr->failed_decrypt_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001599
1600 } else {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001601 /* Woot! Success! Save the name of the crypto block device
1602 * so we can mount it when restarting the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001603 */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001604 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001605
1606 /* Also save a the master key so we can reencrypted the key
1607 * the key when we want to change the password on it.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001608 */
Jason parks70a4b3f2011-01-28 10:10:47 -06001609 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001610 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001611 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001612 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001613 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001614
JP Abgrall7bdfa522013-11-15 13:42:56 -08001615 /*
1616 * Upgrade if we're not using the latest KDF.
1617 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001618 use_keymaster = keymaster_check_compatibility();
1619 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1620 // Don't allow downgrade to KDF_SCRYPT
1621 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1622 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1623 upgrade = 1;
1624 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001625 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001626 upgrade = 1;
1627 }
1628
1629 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001630 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1631 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001632 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001633 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001634 }
1635 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1636 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001637 }
1638
1639 return rc;
1640}
1641
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001642/* Called by vold when it wants to undo the crypto mapping of a volume it
1643 * manages. This is usually in response to a factory reset, when we want
1644 * to undo the crypto mapping so the volume is formatted in the clear.
1645 */
1646int cryptfs_revert_volume(const char *label)
1647{
1648 return delete_crypto_blk_dev((char *)label);
1649}
1650
Ken Sumrall29d8da82011-05-18 17:20:07 -07001651/*
1652 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1653 * Setup a dm-crypt mapping, use the saved master key from
1654 * setting up the /data mapping, and return the new device path.
1655 */
1656int cryptfs_setup_volume(const char *label, int major, int minor,
1657 char *crypto_sys_path, unsigned int max_path,
1658 int *new_major, int *new_minor)
1659{
1660 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1661 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001662 struct stat statbuf;
1663 int nr_sec, fd;
1664
1665 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1666
Ken Sumrall160b4d62013-04-22 12:15:39 -07001667 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001668
1669 /* Update the fs_size field to be the size of the volume */
1670 fd = open(real_blkdev, O_RDONLY);
1671 nr_sec = get_blkdev_size(fd);
1672 close(fd);
1673 if (nr_sec == 0) {
1674 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1675 return -1;
1676 }
1677
1678 sd_crypt_ftr.fs_size = nr_sec;
1679 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1680 crypto_blkdev, label);
1681
1682 stat(crypto_blkdev, &statbuf);
1683 *new_major = MAJOR(statbuf.st_rdev);
1684 *new_minor = MINOR(statbuf.st_rdev);
1685
1686 /* Create path to sys entry for this block device */
1687 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1688
1689 return 0;
1690}
1691
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001692int cryptfs_crypto_complete(void)
1693{
1694 return do_crypto_complete("/data");
1695}
1696
Paul Lawrencef4faa572014-01-29 13:31:03 -08001697int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1698{
1699 char encrypted_state[PROPERTY_VALUE_MAX];
1700 property_get("ro.crypto.state", encrypted_state, "");
1701 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1702 SLOGE("encrypted fs already validated or not running with encryption,"
1703 " aborting");
1704 return -1;
1705 }
1706
1707 if (get_crypt_ftr_and_key(crypt_ftr)) {
1708 SLOGE("Error getting crypt footer and key");
1709 return -1;
1710 }
1711
1712 return 0;
1713}
1714
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001715int cryptfs_check_passwd(char *passwd)
1716{
Paul Lawrencef4faa572014-01-29 13:31:03 -08001717 struct crypt_mnt_ftr crypt_ftr;
1718 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001719
Paul Lawrencef4faa572014-01-29 13:31:03 -08001720 rc = check_unmounted_and_get_ftr(&crypt_ftr);
1721 if (rc)
1722 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001723
Paul Lawrencef4faa572014-01-29 13:31:03 -08001724 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
1725 DATA_MNT_POINT, "userdata");
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001726
1727 if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001728 cryptfs_clear_password();
1729 password = strdup(passwd);
1730 struct timespec now;
1731 clock_gettime(CLOCK_BOOTTIME, &now);
1732 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001733 }
1734
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001735 return rc;
1736}
1737
Ken Sumrall3ad90722011-10-04 20:38:29 -07001738int cryptfs_verify_passwd(char *passwd)
1739{
1740 struct crypt_mnt_ftr crypt_ftr;
1741 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001742 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001743 char encrypted_state[PROPERTY_VALUE_MAX];
1744 int rc;
1745
1746 property_get("ro.crypto.state", encrypted_state, "");
1747 if (strcmp(encrypted_state, "encrypted") ) {
1748 SLOGE("device not encrypted, aborting");
1749 return -2;
1750 }
1751
1752 if (!master_key_saved) {
1753 SLOGE("encrypted fs not yet mounted, aborting");
1754 return -1;
1755 }
1756
1757 if (!saved_mount_point) {
1758 SLOGE("encrypted fs failed to save mount point, aborting");
1759 return -1;
1760 }
1761
Ken Sumrall160b4d62013-04-22 12:15:39 -07001762 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001763 SLOGE("Error getting crypt footer and key\n");
1764 return -1;
1765 }
1766
1767 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1768 /* If the device has no password, then just say the password is valid */
1769 rc = 0;
1770 } else {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001771 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001772 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1773 /* They match, the password is correct */
1774 rc = 0;
1775 } else {
1776 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1777 sleep(1);
1778 rc = 1;
1779 }
1780 }
1781
1782 return rc;
1783}
1784
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001785/* Initialize a crypt_mnt_ftr structure. The keysize is
1786 * defaulted to 16 bytes, and the filesystem size to 0.
1787 * Presumably, at a minimum, the caller will update the
1788 * filesystem size and crypto_type_name after calling this function.
1789 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001790static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001791{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001792 off64_t off;
1793
1794 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001795 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001796 ftr->major_version = CURRENT_MAJOR_VERSION;
1797 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001798 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001799 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001800
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001801 switch (keymaster_check_compatibility()) {
1802 case 1:
1803 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1804 break;
1805
1806 case 0:
1807 ftr->kdf_type = KDF_SCRYPT;
1808 break;
1809
1810 default:
1811 SLOGE("keymaster_check_compatibility failed");
1812 return -1;
1813 }
1814
Kenny Rootc4c70f12013-06-14 12:11:38 -07001815 get_device_scrypt_params(ftr);
1816
Ken Sumrall160b4d62013-04-22 12:15:39 -07001817 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1818 if (get_crypt_ftr_info(NULL, &off) == 0) {
1819 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1820 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1821 ftr->persist_data_size;
1822 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001823
1824 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001825}
1826
Ken Sumrall29d8da82011-05-18 17:20:07 -07001827static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001828{
Ken Sumralle550f782013-08-20 13:48:23 -07001829 const char *args[10];
1830 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1831 int num_args;
1832 int status;
1833 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001834 int rc = -1;
1835
Ken Sumrall29d8da82011-05-18 17:20:07 -07001836 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001837 args[0] = "/system/bin/make_ext4fs";
1838 args[1] = "-a";
1839 args[2] = "/data";
1840 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07001841 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07001842 args[4] = size_str;
1843 args[5] = crypto_blkdev;
1844 num_args = 6;
1845 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1846 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07001847 } else if (type == F2FS_FS) {
1848 args[0] = "/system/bin/mkfs.f2fs";
1849 args[1] = "-t";
1850 args[2] = "-d1";
1851 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07001852 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07001853 args[4] = size_str;
1854 num_args = 5;
1855 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
1856 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001857 } else {
1858 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1859 return -1;
1860 }
1861
Ken Sumralle550f782013-08-20 13:48:23 -07001862 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1863
1864 if (tmp != 0) {
1865 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001866 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07001867 if (WIFEXITED(status)) {
1868 if (WEXITSTATUS(status)) {
1869 SLOGE("Error creating filesystem on %s, exit status %d ",
1870 crypto_blkdev, WEXITSTATUS(status));
1871 } else {
1872 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
1873 rc = 0;
1874 }
1875 } else {
1876 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
1877 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001878 }
1879
1880 return rc;
1881}
1882
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001883#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08001884#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
1885#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001886
1887/* aligned 32K writes tends to make flash happy.
1888 * SD card association recommends it.
1889 */
1890#define BLOCKS_AT_A_TIME 8
1891
1892struct encryptGroupsData
1893{
1894 int realfd;
1895 int cryptofd;
1896 off64_t numblocks;
1897 off64_t one_pct, cur_pct, new_pct;
1898 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07001899 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001900 char* real_blkdev, * crypto_blkdev;
1901 int count;
1902 off64_t offset;
1903 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08001904 off64_t last_written_sector;
1905 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07001906 time_t time_started;
1907 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001908};
1909
Paul Lawrence58c58cf2014-06-04 13:12:21 -07001910static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001911{
1912 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07001913
1914 if (is_used) {
1915 data->used_blocks_already_done++;
1916 }
1917
1918 if (data->tot_used_blocks) {
1919 data->new_pct = data->used_blocks_already_done / data->one_pct;
1920 } else {
1921 data->new_pct = data->blocks_already_done / data->one_pct;
1922 }
1923
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001924 if (data->new_pct > data->cur_pct) {
1925 char buf[8];
1926 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07001927 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001928 property_set("vold.encrypt_progress", buf);
Elliott Hughescb33f572014-06-25 18:25:11 -07001929 SLOGI("Encrypted %" PRId64 " percent of drive", data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001930 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07001931
1932 if (data->cur_pct >= 5) {
1933 double elapsed_time = difftime(time(NULL), data->time_started);
1934 off64_t remaining_blocks = data->tot_used_blocks
1935 - data->used_blocks_already_done;
1936 int remaining_time = (int)(elapsed_time * remaining_blocks
1937 / data->used_blocks_already_done);
1938 if (data->remaining_time == -1
1939 || remaining_time < data->remaining_time) {
1940 char buf[8];
1941 snprintf(buf, sizeof(buf), "%d", remaining_time);
1942 property_set("vold.encrypt_time_remaining", buf);
1943
Elliott Hughescb33f572014-06-25 18:25:11 -07001944 SLOGI("Encrypted %" PRId64 " percent of drive, %d seconds to go",
Paul Lawrencea96d9c92014-06-04 14:05:01 -07001945 data->cur_pct, remaining_time);
1946 data->remaining_time = remaining_time;
1947 }
1948 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001949}
1950
1951static int flush_outstanding_data(struct encryptGroupsData* data)
1952{
1953 if (data->count == 0) {
1954 return 0;
1955 }
1956
Elliott Hughes231bdba2014-06-25 18:36:19 -07001957 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001958
1959 if (pread64(data->realfd, data->buffer,
1960 info.block_size * data->count, data->offset)
1961 <= 0) {
1962 SLOGE("Error reading real_blkdev %s for inplace encrypt",
1963 data->real_blkdev);
1964 return -1;
1965 }
1966
1967 if (pwrite64(data->cryptofd, data->buffer,
1968 info.block_size * data->count, data->offset)
1969 <= 0) {
1970 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
1971 data->crypto_blkdev);
1972 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08001973 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07001974 SLOGI("Encrypted %d blocks at sector %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08001975 data->count, data->offset / info.block_size * CRYPT_SECTOR_SIZE);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001976 }
1977
1978 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08001979 data->last_written_sector = (data->offset + data->count)
1980 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001981 return 0;
1982}
1983
1984static int encrypt_groups(struct encryptGroupsData* data)
1985{
1986 unsigned int i;
1987 u8 *block_bitmap = 0;
1988 unsigned int block;
1989 off64_t ret;
1990 int rc = -1;
1991
1992 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
1993 if (!data->buffer) {
1994 SLOGE("Failed to allocate crypto buffer");
1995 goto errout;
1996 }
1997
1998 block_bitmap = malloc(info.block_size);
1999 if (!block_bitmap) {
2000 SLOGE("failed to allocate block bitmap");
2001 goto errout;
2002 }
2003
2004 for (i = 0; i < aux_info.groups; ++i) {
2005 SLOGI("Encrypting group %d", i);
2006
2007 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2008 u32 block_count = min(info.blocks_per_group,
2009 aux_info.len_blocks - first_block);
2010
2011 off64_t offset = (u64)info.block_size
2012 * aux_info.bg_desc[i].bg_block_bitmap;
2013
2014 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2015 if (ret != (int)info.block_size) {
2016 SLOGE("failed to read all of block group bitmap %d", i);
2017 goto errout;
2018 }
2019
2020 offset = (u64)info.block_size * first_block;
2021
2022 data->count = 0;
2023
2024 for (block = 0; block < block_count; block++) {
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002025 int used = bitmap_get_bit(block_bitmap, block);
2026 update_progress(data, used);
2027 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002028 if (data->count == 0) {
2029 data->offset = offset;
2030 }
2031 data->count++;
2032 } else {
2033 if (flush_outstanding_data(data)) {
2034 goto errout;
2035 }
2036 }
2037
2038 offset += info.block_size;
2039
2040 /* Write data if we are aligned or buffer size reached */
2041 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2042 || data->count == BLOCKS_AT_A_TIME) {
2043 if (flush_outstanding_data(data)) {
2044 goto errout;
2045 }
2046 }
Paul Lawrence87999172014-02-20 12:21:31 -08002047
Paul Lawrence73d7a022014-06-09 14:10:09 -07002048 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002049 SLOGE("Stopping encryption due to low battery");
2050 rc = 0;
2051 goto errout;
2052 }
2053
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002054 }
2055 if (flush_outstanding_data(data)) {
2056 goto errout;
2057 }
2058 }
2059
Paul Lawrence87999172014-02-20 12:21:31 -08002060 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002061 rc = 0;
2062
2063errout:
2064 free(data->buffer);
2065 free(block_bitmap);
2066 return rc;
2067}
2068
2069static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2070 char *real_blkdev,
2071 off64_t size,
2072 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002073 off64_t tot_size,
2074 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002075{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002076 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002077 struct encryptGroupsData data;
2078 int rc = -1;
2079
Paul Lawrence87999172014-02-20 12:21:31 -08002080 if (previously_encrypted_upto > *size_already_done) {
2081 SLOGD("Not fast encrypting since resuming part way through");
2082 return -1;
2083 }
2084
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002085 memset(&data, 0, sizeof(data));
2086 data.real_blkdev = real_blkdev;
2087 data.crypto_blkdev = crypto_blkdev;
2088
2089 if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
2090 SLOGE("Error opening real_blkdev %s for inplace encrypt\n",
2091 real_blkdev);
2092 goto errout;
2093 }
2094
2095 if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
2096 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n",
2097 crypto_blkdev);
2098 goto errout;
2099 }
2100
2101 if (setjmp(setjmp_env)) {
2102 SLOGE("Reading extent caused an exception");
2103 goto errout;
2104 }
2105
2106 if (read_ext(data.realfd, 0) != 0) {
2107 SLOGE("Failed to read extent");
2108 goto errout;
2109 }
2110
2111 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2112 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2113 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2114
2115 SLOGI("Encrypting filesystem in place...");
2116
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002117 data.tot_used_blocks = data.numblocks;
2118 for (i = 0; i < aux_info.groups; ++i) {
2119 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2120 }
2121
2122 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002123 data.cur_pct = 0;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002124 data.time_started = time(NULL);
2125 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002126
2127 rc = encrypt_groups(&data);
2128 if (rc) {
2129 SLOGE("Error encrypting groups");
2130 goto errout;
2131 }
2132
Paul Lawrence87999172014-02-20 12:21:31 -08002133 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002134 rc = 0;
2135
2136errout:
2137 close(data.realfd);
2138 close(data.cryptofd);
2139
2140 return rc;
2141}
2142
2143static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2144 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002145 off64_t tot_size,
2146 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002147{
2148 int realfd, cryptofd;
2149 char *buf[CRYPT_INPLACE_BUFSIZE];
2150 int rc = -1;
2151 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002152 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002153 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002154
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002155 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
2156 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
2157 return -1;
2158 }
2159
2160 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
2161 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
2162 close(realfd);
2163 return -1;
2164 }
2165
2166 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2167 * The size passed in is the number of 512 byte sectors in the filesystem.
2168 * So compute the number of whole 4K blocks we should read/write,
2169 * and the remainder.
2170 */
2171 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2172 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002173 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2174 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002175
2176 SLOGE("Encrypting filesystem in place...");
2177
Paul Lawrence87999172014-02-20 12:21:31 -08002178 i = previously_encrypted_upto + 1 - *size_already_done;
2179
2180 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2181 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2182 goto errout;
2183 }
2184
2185 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2186 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2187 goto errout;
2188 }
2189
2190 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2191 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2192 SLOGE("Error reading initial sectors from real_blkdev %s for "
2193 "inplace encrypt\n", crypto_blkdev);
2194 goto errout;
2195 }
2196 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2197 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2198 "inplace encrypt\n", crypto_blkdev);
2199 goto errout;
2200 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002201 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002202 }
2203 }
2204
Ken Sumrall29d8da82011-05-18 17:20:07 -07002205 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002206 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002207 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002208 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002209 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002210 if (new_pct > cur_pct) {
2211 char buf[8];
2212
2213 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002214 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002215 property_set("vold.encrypt_progress", buf);
2216 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002217 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002218 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002219 goto errout;
2220 }
2221 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002222 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2223 goto errout;
2224 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002225 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002226 CRYPT_SECTORS_PER_BUFSIZE,
2227 i * CRYPT_SECTORS_PER_BUFSIZE);
2228 }
2229
Paul Lawrence73d7a022014-06-09 14:10:09 -07002230 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002231 SLOGE("Stopping encryption due to low battery");
2232 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2233 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002234 goto errout;
2235 }
2236 }
2237
2238 /* Do any remaining sectors */
2239 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002240 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2241 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002242 goto errout;
2243 }
Paul Lawrence87999172014-02-20 12:21:31 -08002244 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2245 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002246 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002247 } else {
2248 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002249 }
2250 }
2251
Ken Sumrall29d8da82011-05-18 17:20:07 -07002252 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002253 rc = 0;
2254
2255errout:
2256 close(realfd);
2257 close(cryptofd);
2258
2259 return rc;
2260}
2261
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002262static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2263 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002264 off64_t tot_size,
2265 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002266{
Paul Lawrence87999172014-02-20 12:21:31 -08002267 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002268 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002269 }
2270
2271 if (*size_already_done + size < previously_encrypted_upto) {
2272 *size_already_done += size;
2273 return 0;
2274 }
2275
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002276 if (cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002277 size, size_already_done,
2278 tot_size, previously_encrypted_upto) == 0) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002279 return 0;
2280 }
2281
2282 return cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002283 size, size_already_done, tot_size,
2284 previously_encrypted_upto);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002285}
2286
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002287#define CRYPTO_ENABLE_WIPE 1
2288#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002289
2290#define FRAMEWORK_BOOT_WAIT 60
2291
Ken Sumrall29d8da82011-05-18 17:20:07 -07002292static inline int should_encrypt(struct volume_info *volume)
2293{
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002294 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
Ken Sumrall29d8da82011-05-18 17:20:07 -07002295 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
2296}
2297
Paul Lawrence87999172014-02-20 12:21:31 -08002298static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2299{
2300 int fd = open(filename, O_RDONLY);
2301 if (fd == -1) {
2302 SLOGE("Error opening file %s", filename);
2303 return -1;
2304 }
2305
2306 char block[CRYPT_INPLACE_BUFSIZE];
2307 memset(block, 0, sizeof(block));
2308 if (unix_read(fd, block, sizeof(block)) < 0) {
2309 SLOGE("Error reading file %s", filename);
2310 close(fd);
2311 return -1;
2312 }
2313
2314 close(fd);
2315
2316 SHA256_CTX c;
2317 SHA256_Init(&c);
2318 SHA256_Update(&c, block, sizeof(block));
2319 SHA256_Final(buf, &c);
2320
2321 return 0;
2322}
2323
JP Abgrall62c7af32014-06-16 13:01:23 -07002324static int get_fs_type(struct fstab_rec *rec)
2325{
2326 if (!strcmp(rec->fs_type, "ext4")) {
2327 return EXT4_FS;
2328 } else if (!strcmp(rec->fs_type, "f2fs")) {
2329 return F2FS_FS;
2330 } else {
2331 return -1;
2332 }
2333}
2334
Paul Lawrence87999172014-02-20 12:21:31 -08002335static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2336 char *crypto_blkdev, char *real_blkdev,
2337 int previously_encrypted_upto)
2338{
2339 off64_t cur_encryption_done=0, tot_encryption_size=0;
2340 int i, rc = -1;
2341
Paul Lawrence73d7a022014-06-09 14:10:09 -07002342 if (!is_battery_ok_to_start()) {
2343 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002344 return 0;
2345 }
2346
2347 /* The size of the userdata partition, and add in the vold volumes below */
2348 tot_encryption_size = crypt_ftr->fs_size;
2349
2350 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002351 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2352 int fs_type = get_fs_type(rec);
2353 if (fs_type < 0) {
2354 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2355 return -1;
2356 }
2357 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002358 } else if (how == CRYPTO_ENABLE_INPLACE) {
2359 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2360 crypt_ftr->fs_size, &cur_encryption_done,
2361 tot_encryption_size,
2362 previously_encrypted_upto);
2363
Paul Lawrence73d7a022014-06-09 14:10:09 -07002364 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002365 crypt_ftr->encrypted_upto = cur_encryption_done;
2366 }
2367
Paul Lawrence73d7a022014-06-09 14:10:09 -07002368 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002369 /* The inplace routine never actually sets the progress to 100% due
2370 * to the round down nature of integer division, so set it here */
2371 property_set("vold.encrypt_progress", "100");
2372 }
2373 } else {
2374 /* Shouldn't happen */
2375 SLOGE("cryptfs_enable: internal error, unknown option\n");
2376 rc = -1;
2377 }
2378
2379 return rc;
2380}
2381
Paul Lawrence13486032014-02-03 13:28:11 -08002382int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
2383 int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002384{
2385 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002386 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07002387 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002388 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07002389 int rc=-1, fd, i, ret;
Paul Lawrence87999172014-02-20 12:21:31 -08002390 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002391 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002392 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002393 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002394 char key_loc[PROPERTY_VALUE_MAX];
2395 char fuse_sdcard[PROPERTY_VALUE_MAX];
2396 char *sd_mnt_point;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002397 int num_vols;
2398 struct volume_info *vol_list = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002399 off64_t previously_encrypted_upto = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002400
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002401 if (!strcmp(howarg, "wipe")) {
2402 how = CRYPTO_ENABLE_WIPE;
2403 } else if (! strcmp(howarg, "inplace")) {
2404 how = CRYPTO_ENABLE_INPLACE;
2405 } else {
2406 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002407 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002408 }
2409
Paul Lawrence87999172014-02-20 12:21:31 -08002410 /* See if an encryption was underway and interrupted */
2411 if (how == CRYPTO_ENABLE_INPLACE
2412 && get_crypt_ftr_and_key(&crypt_ftr) == 0
2413 && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
2414 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2415 crypt_ftr.encrypted_upto = 0;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002416 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
2417
2418 /* At this point, we are in an inconsistent state. Until we successfully
2419 complete encryption, a reboot will leave us broken. So mark the
2420 encryption failed in case that happens.
2421 On successfully completing encryption, remove this flag */
2422 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2423
2424 put_crypt_ftr_and_key(&crypt_ftr);
Paul Lawrence87999172014-02-20 12:21:31 -08002425 }
2426
2427 property_get("ro.crypto.state", encrypted_state, "");
2428 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2429 SLOGE("Device is already running encrypted, aborting");
2430 goto error_unencrypted;
2431 }
2432
2433 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2434 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002435 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002436
Ken Sumrall3ed82362011-01-28 23:31:16 -08002437 /* Get the size of the real block device */
2438 fd = open(real_blkdev, O_RDONLY);
2439 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
2440 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2441 goto error_unencrypted;
2442 }
2443 close(fd);
2444
2445 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002446 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002447 unsigned int fs_size_sec, max_fs_size_sec;
2448
2449 fs_size_sec = get_fs_size(real_blkdev);
Paul Lawrence87999172014-02-20 12:21:31 -08002450 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002451
2452 if (fs_size_sec > max_fs_size_sec) {
2453 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2454 goto error_unencrypted;
2455 }
2456 }
2457
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002458 /* Get a wakelock as this may take a while, and we don't want the
2459 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2460 * wants to keep the screen on, it can grab a full wakelock.
2461 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002462 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002463 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2464
Jeff Sharkey7382f812012-08-23 14:08:59 -07002465 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07002466 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07002467 if (!sd_mnt_point) {
2468 sd_mnt_point = getenv("EXTERNAL_STORAGE");
2469 }
2470 if (!sd_mnt_point) {
2471 sd_mnt_point = "/mnt/sdcard";
2472 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07002473
Paul Lawrence87999172014-02-20 12:21:31 -08002474 /* TODO
2475 * Currently do not have test devices with multiple encryptable volumes.
2476 * When we acquire some, re-add support.
2477 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002478 num_vols=vold_getNumDirectVolumes();
2479 vol_list = malloc(sizeof(struct volume_info) * num_vols);
2480 vold_getDirectVolumeList(vol_list);
2481
2482 for (i=0; i<num_vols; i++) {
2483 if (should_encrypt(&vol_list[i])) {
Paul Lawrence87999172014-02-20 12:21:31 -08002484 SLOGE("Cannot encrypt if there are multiple encryptable volumes"
2485 "%s\n", vol_list[i].label);
2486 goto error_unencrypted;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002487 }
2488 }
2489
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002490 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002491 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002492 */
2493 property_set("vold.decrypt", "trigger_shutdown_framework");
2494 SLOGD("Just asked init to shut down class main\n");
2495
Ken Sumrall425524d2012-06-14 20:55:28 -07002496 if (vold_unmountAllAsecs()) {
2497 /* Just report the error. If any are left mounted,
2498 * umounting /data below will fail and handle the error.
2499 */
2500 SLOGE("Error unmounting internal asecs");
2501 }
2502
Ken Sumrall29d8da82011-05-18 17:20:07 -07002503 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
2504 if (!strcmp(fuse_sdcard, "true")) {
2505 /* This is a device using the fuse layer to emulate the sdcard semantics
2506 * on top of the userdata partition. vold does not manage it, it is managed
2507 * by the sdcard service. The sdcard service was killed by the property trigger
2508 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
2509 * unlike the case for vold managed devices above.
2510 */
2511 if (wait_and_unmount(sd_mnt_point)) {
2512 goto error_shutting_down;
2513 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002514 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002515
2516 /* Now unmount the /data partition. */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002517 if (wait_and_unmount(DATA_MNT_POINT)) {
JP Abgrall502dc742013-11-01 13:06:20 -07002518 if (allow_reboot) {
2519 goto error_shutting_down;
2520 } else {
2521 goto error_unencrypted;
2522 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002523 }
2524
2525 /* Do extra work for a better UX when doing the long inplace encryption */
2526 if (how == CRYPTO_ENABLE_INPLACE) {
2527 /* Now that /data is unmounted, we need to mount a tmpfs
2528 * /data, set a property saying we're doing inplace encryption,
2529 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002530 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002531 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002532 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002533 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002534 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002535 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002536
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002537 /* restart the framework. */
2538 /* Create necessary paths on /data */
2539 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002540 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002541 }
2542
Ken Sumrall92736ef2012-10-17 20:57:14 -07002543 /* Ugh, shutting down the framework is not synchronous, so until it
2544 * can be fixed, this horrible hack will wait a moment for it all to
2545 * shut down before proceeding. Without it, some devices cannot
2546 * restart the graphics services.
2547 */
2548 sleep(2);
2549
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002550 /* startup service classes main and late_start */
2551 property_set("vold.decrypt", "trigger_restart_min_framework");
2552 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002553
Ken Sumrall7df84122011-01-18 14:04:08 -08002554 /* OK, the framework is restarted and will soon be showing a
2555 * progress bar. Time to setup an encrypted mapping, and
2556 * either write a new filesystem, or encrypt in place updating
2557 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002558 */
2559 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002560
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002561 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002562 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence87999172014-02-20 12:21:31 -08002563 if (previously_encrypted_upto == 0) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002564 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2565 goto error_shutting_down;
2566 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002567
Paul Lawrence87999172014-02-20 12:21:31 -08002568 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2569 crypt_ftr.fs_size = nr_sec
2570 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2571 } else {
2572 crypt_ftr.fs_size = nr_sec;
2573 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002574 /* At this point, we are in an inconsistent state. Until we successfully
2575 complete encryption, a reboot will leave us broken. So mark the
2576 encryption failed in case that happens.
2577 On successfully completing encryption, remove this flag */
2578 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence87999172014-02-20 12:21:31 -08002579 crypt_ftr.crypt_type = crypt_type;
2580 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002581
Paul Lawrence87999172014-02-20 12:21:31 -08002582 /* Make an encrypted master key */
2583 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
2584 SLOGE("Cannot create encrypted master key\n");
2585 goto error_shutting_down;
2586 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002587
Paul Lawrence87999172014-02-20 12:21:31 -08002588 /* Write the key to the end of the partition */
2589 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002590
Paul Lawrence87999172014-02-20 12:21:31 -08002591 /* If any persistent data has been remembered, save it.
2592 * If none, create a valid empty table and save that.
2593 */
2594 if (!persist_data) {
2595 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
2596 if (pdata) {
2597 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2598 persist_data = pdata;
2599 }
2600 }
2601 if (persist_data) {
2602 save_persistent_data();
2603 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002604 }
2605
JP Abgrall7bdfa522013-11-15 13:42:56 -08002606 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002607 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
2608 "userdata");
2609
Paul Lawrence87999172014-02-20 12:21:31 -08002610 /* If we are continuing, check checksums match */
2611 rc = 0;
2612 if (previously_encrypted_upto) {
2613 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2614 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002615
Paul Lawrence87999172014-02-20 12:21:31 -08002616 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2617 sizeof(hash_first_block)) != 0) {
2618 SLOGE("Checksums do not match - trigger wipe");
2619 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002620 }
2621 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002622
Paul Lawrence87999172014-02-20 12:21:31 -08002623 if (!rc) {
2624 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
2625 crypto_blkdev, real_blkdev,
2626 previously_encrypted_upto);
2627 }
2628
2629 /* Calculate checksum if we are not finished */
Paul Lawrence73d7a022014-06-09 14:10:09 -07002630 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002631 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2632 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002633 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002634 SLOGE("Error calculating checksum for continuing encryption");
2635 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002636 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002637 }
2638
2639 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002640 delete_crypto_blk_dev("userdata");
Ken Sumrall29d8da82011-05-18 17:20:07 -07002641
2642 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002643
2644 if (! rc) {
2645 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002646 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002647
Paul Lawrence6bfed202014-07-28 12:47:22 -07002648 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002649 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2650 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002651 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002652 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002653
Paul Lawrence6bfed202014-07-28 12:47:22 -07002654 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002655
Ken Sumrall29d8da82011-05-18 17:20:07 -07002656 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08002657 /* Partially encrypted - ensure writes are flushed to ssd */
2658
Paul Lawrence73d7a022014-06-09 14:10:09 -07002659 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002660 cryptfs_reboot(reboot);
2661 } else {
2662 cryptfs_reboot(shutdown);
2663 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002664 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002665 char value[PROPERTY_VALUE_MAX];
2666
Ken Sumrall319369a2012-06-27 16:30:18 -07002667 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002668 if (!strcmp(value, "1")) {
2669 /* wipe data if encryption failed */
2670 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
2671 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07002672 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002673 if (fd >= 0) {
2674 write(fd, "--wipe_data", strlen("--wipe_data") + 1);
2675 close(fd);
2676 } else {
2677 SLOGE("could not open /cache/recovery/command\n");
2678 }
Paul Lawrence87999172014-02-20 12:21:31 -08002679 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002680 } else {
2681 /* set property to trigger dialog */
2682 property_set("vold.encrypt_progress", "error_partially_encrypted");
2683 release_wake_lock(lockid);
2684 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002685 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002686 }
2687
Ken Sumrall3ed82362011-01-28 23:31:16 -08002688 /* hrm, the encrypt step claims success, but the reboot failed.
2689 * This should not happen.
2690 * Set the property and return. Hope the framework can deal with it.
2691 */
2692 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002693 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002694 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002695
2696error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07002697 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002698 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002699 if (lockid[0]) {
2700 release_wake_lock(lockid);
2701 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002702 return -1;
2703
2704error_shutting_down:
2705 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2706 * but the framework is stopped and not restarted to show the error, so it's up to
2707 * vold to restart the system.
2708 */
2709 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08002710 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002711
2712 /* shouldn't get here */
2713 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07002714 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002715 if (lockid[0]) {
2716 release_wake_lock(lockid);
2717 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002718 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002719}
2720
Paul Lawrence45f10532014-04-04 18:11:56 +00002721int cryptfs_enable(char *howarg, int type, char *passwd, int allow_reboot)
Paul Lawrence13486032014-02-03 13:28:11 -08002722{
Paul Lawrence45f10532014-04-04 18:11:56 +00002723 return cryptfs_enable_internal(howarg, type, passwd, allow_reboot);
Paul Lawrence13486032014-02-03 13:28:11 -08002724}
2725
2726int cryptfs_enable_default(char *howarg, int allow_reboot)
2727{
2728 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
2729 DEFAULT_PASSWORD, allow_reboot);
2730}
2731
2732int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002733{
2734 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002735 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002736
2737 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002738 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002739 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002740 return -1;
2741 }
2742
Paul Lawrencef4faa572014-01-29 13:31:03 -08002743 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2744 SLOGE("Invalid crypt_type %d", crypt_type);
2745 return -1;
2746 }
2747
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002748 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002749 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002750 SLOGE("Error getting crypt footer and key");
2751 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002752 }
2753
Paul Lawrencef4faa572014-01-29 13:31:03 -08002754 crypt_ftr.crypt_type = crypt_type;
2755
2756 encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
2757 : newpw,
2758 crypt_ftr.salt,
2759 saved_master_key,
2760 crypt_ftr.master_key,
2761 &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002762
Jason parks70a4b3f2011-01-28 10:10:47 -06002763 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002764 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002765
2766 return 0;
2767}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002768
2769static int persist_get_key(char *fieldname, char *value)
2770{
2771 unsigned int i;
2772
2773 if (persist_data == NULL) {
2774 return -1;
2775 }
2776 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2777 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2778 /* We found it! */
2779 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2780 return 0;
2781 }
2782 }
2783
2784 return -1;
2785}
2786
2787static int persist_set_key(char *fieldname, char *value, int encrypted)
2788{
2789 unsigned int i;
2790 unsigned int num;
2791 struct crypt_mnt_ftr crypt_ftr;
2792 unsigned int max_persistent_entries;
2793 unsigned int dsize;
2794
2795 if (persist_data == NULL) {
2796 return -1;
2797 }
2798
2799 /* If encrypted, use the values from the crypt_ftr, otherwise
2800 * use the values for the current spec.
2801 */
2802 if (encrypted) {
2803 if(get_crypt_ftr_and_key(&crypt_ftr)) {
2804 return -1;
2805 }
2806 dsize = crypt_ftr.persist_data_size;
2807 } else {
2808 dsize = CRYPT_PERSIST_DATA_SIZE;
2809 }
2810 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2811 sizeof(struct crypt_persist_entry);
2812
2813 num = persist_data->persist_valid_entries;
2814
2815 for (i = 0; i < num; i++) {
2816 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2817 /* We found an existing entry, update it! */
2818 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2819 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2820 return 0;
2821 }
2822 }
2823
2824 /* We didn't find it, add it to the end, if there is room */
2825 if (persist_data->persist_valid_entries < max_persistent_entries) {
2826 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2827 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2828 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2829 persist_data->persist_valid_entries++;
2830 return 0;
2831 }
2832
2833 return -1;
2834}
2835
2836/* Return the value of the specified field. */
2837int cryptfs_getfield(char *fieldname, char *value, int len)
2838{
2839 char temp_value[PROPERTY_VALUE_MAX];
2840 char real_blkdev[MAXPATHLEN];
2841 /* 0 is success, 1 is not encrypted,
2842 * -1 is value not set, -2 is any other error
2843 */
2844 int rc = -2;
2845
2846 if (persist_data == NULL) {
2847 load_persistent_data();
2848 if (persist_data == NULL) {
2849 SLOGE("Getfield error, cannot load persistent data");
2850 goto out;
2851 }
2852 }
2853
2854 if (!persist_get_key(fieldname, temp_value)) {
2855 /* We found it, copy it to the caller's buffer and return */
2856 strlcpy(value, temp_value, len);
2857 rc = 0;
2858 } else {
2859 /* Sadness, it's not there. Return the error */
2860 rc = -1;
2861 }
2862
2863out:
2864 return rc;
2865}
2866
2867/* Set the value of the specified field. */
2868int cryptfs_setfield(char *fieldname, char *value)
2869{
2870 struct crypt_persist_data stored_pdata;
2871 struct crypt_persist_data *pdata_p;
2872 struct crypt_mnt_ftr crypt_ftr;
2873 char encrypted_state[PROPERTY_VALUE_MAX];
2874 /* 0 is success, -1 is an error */
2875 int rc = -1;
2876 int encrypted = 0;
2877
2878 if (persist_data == NULL) {
2879 load_persistent_data();
2880 if (persist_data == NULL) {
2881 SLOGE("Setfield error, cannot load persistent data");
2882 goto out;
2883 }
2884 }
2885
2886 property_get("ro.crypto.state", encrypted_state, "");
2887 if (!strcmp(encrypted_state, "encrypted") ) {
2888 encrypted = 1;
2889 }
2890
2891 if (persist_set_key(fieldname, value, encrypted)) {
2892 goto out;
2893 }
2894
2895 /* If we are running encrypted, save the persistent data now */
2896 if (encrypted) {
2897 if (save_persistent_data()) {
2898 SLOGE("Setfield error, cannot save persistent data");
2899 goto out;
2900 }
2901 }
2902
2903 rc = 0;
2904
2905out:
2906 return rc;
2907}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002908
2909/* Checks userdata. Attempt to mount the volume if default-
2910 * encrypted.
2911 * On success trigger next init phase and return 0.
2912 * Currently do not handle failure - see TODO below.
2913 */
2914int cryptfs_mount_default_encrypted(void)
2915{
2916 char decrypt_state[PROPERTY_VALUE_MAX];
2917 property_get("vold.decrypt", decrypt_state, "0");
2918 if (!strcmp(decrypt_state, "0")) {
2919 SLOGE("Not encrypted - should not call here");
2920 } else {
2921 int crypt_type = cryptfs_get_password_type();
2922 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2923 SLOGE("Bad crypt type - error");
2924 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2925 SLOGD("Password is not default - "
2926 "starting min framework to prompt");
2927 property_set("vold.decrypt", "trigger_restart_min_framework");
2928 return 0;
2929 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2930 SLOGD("Password is default - restarting filesystem");
2931 cryptfs_restart_internal(0);
2932 return 0;
2933 } else {
2934 SLOGE("Encrypted, default crypt type but can't decrypt");
2935 }
2936 }
2937
Paul Lawrence6bfed202014-07-28 12:47:22 -07002938 /** Corrupt. Allow us to boot into framework, which will detect bad
2939 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08002940 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002941 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002942 return 0;
2943}
2944
2945/* Returns type of the password, default, pattern, pin or password.
2946 */
2947int cryptfs_get_password_type(void)
2948{
2949 struct crypt_mnt_ftr crypt_ftr;
2950
2951 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2952 SLOGE("Error getting crypt footer and key\n");
2953 return -1;
2954 }
2955
Paul Lawrence6bfed202014-07-28 12:47:22 -07002956 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2957 return -1;
2958 }
2959
Paul Lawrencef4faa572014-01-29 13:31:03 -08002960 return crypt_ftr.crypt_type;
2961}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002962
Paul Lawrence399317e2014-03-10 13:20:50 -07002963char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002964{
Paul Lawrence399317e2014-03-10 13:20:50 -07002965 struct timespec now;
2966 clock_gettime(CLOCK_MONOTONIC, &now);
2967 if (now.tv_sec < password_expiry_time) {
2968 return password;
2969 } else {
2970 cryptfs_clear_password();
2971 return 0;
2972 }
2973}
2974
2975void cryptfs_clear_password()
2976{
2977 if (password) {
2978 size_t len = strlen(password);
2979 memset(password, 0, len);
2980 free(password);
2981 password = 0;
2982 password_expiry_time = 0;
2983 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002984}