blob: 87bf779ad4f721a188335585d902fceae6ff41b4 [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>
26#include <fcntl.h>
27#include <unistd.h>
28#include <stdio.h>
29#include <sys/ioctl.h>
30#include <linux/dm-ioctl.h>
31#include <libgen.h>
32#include <stdlib.h>
33#include <sys/param.h>
34#include <string.h>
35#include <sys/mount.h>
36#include <openssl/evp.h>
Ken Sumrall8ddbe402011-01-17 15:26:29 -080037#include <openssl/sha.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080038#include <errno.h>
Ken Sumrall3ed82362011-01-28 23:31:16 -080039#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070040#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070041#include <fs_mgr.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080042#include "cryptfs.h"
43#define LOG_TAG "Cryptfs"
44#include "cutils/log.h"
45#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070046#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080047#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070048#include <logwrap/logwrap.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070049#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070050#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070051#include "crypto_scrypt.h"
Paul Lawrenceae59fe62014-01-21 08:23:27 -080052#include "ext4_utils.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080053
54#define DM_CRYPT_BUF_SIZE 4096
55
Jason parks70a4b3f2011-01-28 10:10:47 -060056#define HASH_COUNT 2000
57#define KEY_LEN_BYTES 16
58#define IV_LEN_BYTES 16
59
Ken Sumrall29d8da82011-05-18 17:20:07 -070060#define KEY_IN_FOOTER "footer"
61
62#define EXT4_FS 1
63#define FAT_FS 2
64
Ken Sumralle919efe2012-09-29 17:07:41 -070065#define TABLE_LOAD_RETRIES 10
66
Ken Sumrall8f869aa2010-12-03 03:47:09 -080067char *me = "cryptfs";
68
Jason parks70a4b3f2011-01-28 10:10:47 -060069static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070070static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060071static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -070072static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -080073
74extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -080075
Ken Sumralladfba362013-06-04 16:37:52 -070076static void cryptfs_reboot(int recovery)
77{
78 if (recovery) {
79 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
80 } else {
81 property_set(ANDROID_RB_PROPERTY, "reboot");
82 }
83 sleep(20);
84
85 /* Shouldn't get here, reboot should happen before sleep times out */
86 return;
87}
88
Ken Sumrall8f869aa2010-12-03 03:47:09 -080089static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
90{
91 memset(io, 0, dataSize);
92 io->data_size = dataSize;
93 io->data_start = sizeof(struct dm_ioctl);
94 io->version[0] = 4;
95 io->version[1] = 0;
96 io->version[2] = 0;
97 io->flags = flags;
98 if (name) {
99 strncpy(io->name, name, sizeof(io->name));
100 }
101}
102
Kenny Rootc4c70f12013-06-14 12:11:38 -0700103/**
104 * Gets the default device scrypt parameters for key derivation time tuning.
105 * The parameters should lead to about one second derivation time for the
106 * given device.
107 */
108static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
109 const int default_params[] = SCRYPT_DEFAULTS;
110 int params[] = SCRYPT_DEFAULTS;
111 char paramstr[PROPERTY_VALUE_MAX];
112 char *token;
113 char *saveptr;
114 int i;
115
116 property_get(SCRYPT_PROP, paramstr, "");
117 if (paramstr[0] != '\0') {
118 /*
119 * The token we're looking for should be three integers separated by
120 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
121 */
Kenny Root2947e342013-08-14 15:54:49 -0700122 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
123 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700124 i++, token = strtok_r(NULL, ":", &saveptr)) {
125 char *endptr;
126 params[i] = strtol(token, &endptr, 10);
127
128 /*
129 * Check that there was a valid number and it's 8-bit. If not,
130 * break out and the end check will take the default values.
131 */
132 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
133 break;
134 }
135 }
136
137 /*
138 * If there were not enough tokens or a token was malformed (not an
139 * integer), it will end up here and the default parameters can be
140 * taken.
141 */
142 if ((i != 3) || (token != NULL)) {
143 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
144 memcpy(params, default_params, sizeof(params));
145 }
146 }
147
148 ftr->N_factor = params[0];
149 ftr->r_factor = params[1];
150 ftr->p_factor = params[2];
151}
152
Ken Sumrall3ed82362011-01-28 23:31:16 -0800153static unsigned int get_fs_size(char *dev)
154{
155 int fd, block_size;
156 struct ext4_super_block sb;
157 off64_t len;
158
159 if ((fd = open(dev, O_RDONLY)) < 0) {
160 SLOGE("Cannot open device to get filesystem size ");
161 return 0;
162 }
163
164 if (lseek64(fd, 1024, SEEK_SET) < 0) {
165 SLOGE("Cannot seek to superblock");
166 return 0;
167 }
168
169 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
170 SLOGE("Cannot read superblock");
171 return 0;
172 }
173
174 close(fd);
175
176 block_size = 1024 << sb.s_log_block_size;
177 /* compute length in bytes */
178 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
179
180 /* return length in sectors */
181 return (unsigned int) (len / 512);
182}
183
Ken Sumrall160b4d62013-04-22 12:15:39 -0700184static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
185{
186 static int cached_data = 0;
187 static off64_t cached_off = 0;
188 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
189 int fd;
190 char key_loc[PROPERTY_VALUE_MAX];
191 char real_blkdev[PROPERTY_VALUE_MAX];
192 unsigned int nr_sec;
193 int rc = -1;
194
195 if (!cached_data) {
196 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
197
198 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
199 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
200 SLOGE("Cannot open real block device %s\n", real_blkdev);
201 return -1;
202 }
203
204 if ((nr_sec = get_blkdev_size(fd))) {
205 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
206 * encryption info footer and key, and plenty of bytes to spare for future
207 * growth.
208 */
209 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
210 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
211 cached_data = 1;
212 } else {
213 SLOGE("Cannot get size of block device %s\n", real_blkdev);
214 }
215 close(fd);
216 } else {
217 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
218 cached_off = 0;
219 cached_data = 1;
220 }
221 }
222
223 if (cached_data) {
224 if (metadata_fname) {
225 *metadata_fname = cached_metadata_fname;
226 }
227 if (off) {
228 *off = cached_off;
229 }
230 rc = 0;
231 }
232
233 return rc;
234}
235
Ken Sumralle8744072011-01-18 22:01:55 -0800236/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800237 * update the failed mount count but not change the key.
238 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700239static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800240{
241 int fd;
242 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700243 /* starting_off is set to the SEEK_SET offset
244 * where the crypto structure starts
245 */
246 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800247 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700248 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700249 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800250
Ken Sumrall160b4d62013-04-22 12:15:39 -0700251 if (get_crypt_ftr_info(&fname, &starting_off)) {
252 SLOGE("Unable to get crypt_ftr_info\n");
253 return -1;
254 }
255 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700256 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700257 return -1;
258 }
Ken Sumralle550f782013-08-20 13:48:23 -0700259 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
260 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700261 return -1;
262 }
263
264 /* Seek to the start of the crypt footer */
265 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
266 SLOGE("Cannot seek to real block device footer\n");
267 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800268 }
269
270 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
271 SLOGE("Cannot write real block device footer\n");
272 goto errout;
273 }
274
Ken Sumrall3be890f2011-09-14 16:53:46 -0700275 fstat(fd, &statbuf);
276 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700277 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700278 if (ftruncate(fd, 0x4000)) {
Ken Sumrall3be890f2011-09-14 16:53:46 -0700279 SLOGE("Cannot set footer file size\n", fname);
Ken Sumralle8744072011-01-18 22:01:55 -0800280 goto errout;
281 }
282 }
283
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800284 /* Success! */
285 rc = 0;
286
287errout:
288 close(fd);
289 return rc;
290
291}
292
Ken Sumrall160b4d62013-04-22 12:15:39 -0700293static inline int unix_read(int fd, void* buff, int len)
294{
295 return TEMP_FAILURE_RETRY(read(fd, buff, len));
296}
297
298static inline int unix_write(int fd, const void* buff, int len)
299{
300 return TEMP_FAILURE_RETRY(write(fd, buff, len));
301}
302
303static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
304{
305 memset(pdata, 0, len);
306 pdata->persist_magic = PERSIST_DATA_MAGIC;
307 pdata->persist_valid_entries = 0;
308}
309
310/* A routine to update the passed in crypt_ftr to the lastest version.
311 * fd is open read/write on the device that holds the crypto footer and persistent
312 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
313 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
314 */
315static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
316{
Kenny Root7434b312013-06-14 11:29:53 -0700317 int orig_major = crypt_ftr->major_version;
318 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700319
Kenny Root7434b312013-06-14 11:29:53 -0700320 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
321 struct crypt_persist_data *pdata;
322 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700323
Kenny Rootc4c70f12013-06-14 12:11:38 -0700324 SLOGW("upgrading crypto footer to 1.1");
325
Kenny Root7434b312013-06-14 11:29:53 -0700326 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
327 if (pdata == NULL) {
328 SLOGE("Cannot allocate persisent data\n");
329 return;
330 }
331 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
332
333 /* Need to initialize the persistent data area */
334 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
335 SLOGE("Cannot seek to persisent data offset\n");
336 return;
337 }
338 /* Write all zeros to the first copy, making it invalid */
339 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
340
341 /* Write a valid but empty structure to the second copy */
342 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
343 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
344
345 /* Update the footer */
346 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
347 crypt_ftr->persist_data_offset[0] = pdata_offset;
348 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
349 crypt_ftr->minor_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700350 }
351
Kenny Rootc4c70f12013-06-14 12:11:38 -0700352 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version)) {
353 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800354 /* But keep the old kdf_type.
355 * It will get updated later to KDF_SCRYPT after the password has been verified.
356 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700357 crypt_ftr->kdf_type = KDF_PBKDF2;
358 get_device_scrypt_params(crypt_ftr);
359 crypt_ftr->minor_version = 2;
360 }
361
Kenny Root7434b312013-06-14 11:29:53 -0700362 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
363 if (lseek64(fd, offset, SEEK_SET) == -1) {
364 SLOGE("Cannot seek to crypt footer\n");
365 return;
366 }
367 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700368 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700369}
370
371
372static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800373{
374 int fd;
375 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700376 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800377 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700378 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700379 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800380
Ken Sumrall160b4d62013-04-22 12:15:39 -0700381 if (get_crypt_ftr_info(&fname, &starting_off)) {
382 SLOGE("Unable to get crypt_ftr_info\n");
383 return -1;
384 }
385 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700386 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700387 return -1;
388 }
389 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700390 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700391 return -1;
392 }
393
394 /* Make sure it's 16 Kbytes in length */
395 fstat(fd, &statbuf);
396 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
397 SLOGE("footer file %s is not the expected size!\n", fname);
398 goto errout;
399 }
400
401 /* Seek to the start of the crypt footer */
402 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
403 SLOGE("Cannot seek to real block device footer\n");
404 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800405 }
406
407 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
408 SLOGE("Cannot read real block device footer\n");
409 goto errout;
410 }
411
412 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700413 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800414 goto errout;
415 }
416
Kenny Rootc96a5f82013-06-14 12:08:28 -0700417 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
418 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
419 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800420 goto errout;
421 }
422
Kenny Rootc96a5f82013-06-14 12:08:28 -0700423 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
424 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
425 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800426 }
427
Ken Sumrall160b4d62013-04-22 12:15:39 -0700428 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
429 * copy on disk before returning.
430 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700431 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700432 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800433 }
434
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800435 /* Success! */
436 rc = 0;
437
438errout:
439 close(fd);
440 return rc;
441}
442
Ken Sumrall160b4d62013-04-22 12:15:39 -0700443static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
444{
445 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
446 crypt_ftr->persist_data_offset[1]) {
447 SLOGE("Crypt_ftr persist data regions overlap");
448 return -1;
449 }
450
451 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
452 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
453 return -1;
454 }
455
456 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
457 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
458 CRYPT_FOOTER_OFFSET) {
459 SLOGE("Persistent data extends past crypto footer");
460 return -1;
461 }
462
463 return 0;
464}
465
466static int load_persistent_data(void)
467{
468 struct crypt_mnt_ftr crypt_ftr;
469 struct crypt_persist_data *pdata = NULL;
470 char encrypted_state[PROPERTY_VALUE_MAX];
471 char *fname;
472 int found = 0;
473 int fd;
474 int ret;
475 int i;
476
477 if (persist_data) {
478 /* Nothing to do, we've already loaded or initialized it */
479 return 0;
480 }
481
482
483 /* If not encrypted, just allocate an empty table and initialize it */
484 property_get("ro.crypto.state", encrypted_state, "");
485 if (strcmp(encrypted_state, "encrypted") ) {
486 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
487 if (pdata) {
488 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
489 persist_data = pdata;
490 return 0;
491 }
492 return -1;
493 }
494
495 if(get_crypt_ftr_and_key(&crypt_ftr)) {
496 return -1;
497 }
498
499 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
500 SLOGE("Crypt_ftr version doesn't support persistent data");
501 return -1;
502 }
503
504 if (get_crypt_ftr_info(&fname, NULL)) {
505 return -1;
506 }
507
508 ret = validate_persistent_data_storage(&crypt_ftr);
509 if (ret) {
510 return -1;
511 }
512
513 fd = open(fname, O_RDONLY);
514 if (fd < 0) {
515 SLOGE("Cannot open %s metadata file", fname);
516 return -1;
517 }
518
519 if (persist_data == NULL) {
520 pdata = malloc(crypt_ftr.persist_data_size);
521 if (pdata == NULL) {
522 SLOGE("Cannot allocate memory for persistent data");
523 goto err;
524 }
525 }
526
527 for (i = 0; i < 2; i++) {
528 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
529 SLOGE("Cannot seek to read persistent data on %s", fname);
530 goto err2;
531 }
532 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
533 SLOGE("Error reading persistent data on iteration %d", i);
534 goto err2;
535 }
536 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
537 found = 1;
538 break;
539 }
540 }
541
542 if (!found) {
543 SLOGI("Could not find valid persistent data, creating");
544 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
545 }
546
547 /* Success */
548 persist_data = pdata;
549 close(fd);
550 return 0;
551
552err2:
553 free(pdata);
554
555err:
556 close(fd);
557 return -1;
558}
559
560static int save_persistent_data(void)
561{
562 struct crypt_mnt_ftr crypt_ftr;
563 struct crypt_persist_data *pdata;
564 char *fname;
565 off64_t write_offset;
566 off64_t erase_offset;
567 int found = 0;
568 int fd;
569 int ret;
570
571 if (persist_data == NULL) {
572 SLOGE("No persistent data to save");
573 return -1;
574 }
575
576 if(get_crypt_ftr_and_key(&crypt_ftr)) {
577 return -1;
578 }
579
580 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
581 SLOGE("Crypt_ftr version doesn't support persistent data");
582 return -1;
583 }
584
585 ret = validate_persistent_data_storage(&crypt_ftr);
586 if (ret) {
587 return -1;
588 }
589
590 if (get_crypt_ftr_info(&fname, NULL)) {
591 return -1;
592 }
593
594 fd = open(fname, O_RDWR);
595 if (fd < 0) {
596 SLOGE("Cannot open %s metadata file", fname);
597 return -1;
598 }
599
600 pdata = malloc(crypt_ftr.persist_data_size);
601 if (pdata == NULL) {
602 SLOGE("Cannot allocate persistant data");
603 goto err;
604 }
605
606 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
607 SLOGE("Cannot seek to read persistent data on %s", fname);
608 goto err2;
609 }
610
611 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
612 SLOGE("Error reading persistent data before save");
613 goto err2;
614 }
615
616 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
617 /* The first copy is the curent valid copy, so write to
618 * the second copy and erase this one */
619 write_offset = crypt_ftr.persist_data_offset[1];
620 erase_offset = crypt_ftr.persist_data_offset[0];
621 } else {
622 /* The second copy must be the valid copy, so write to
623 * the first copy, and erase the second */
624 write_offset = crypt_ftr.persist_data_offset[0];
625 erase_offset = crypt_ftr.persist_data_offset[1];
626 }
627
628 /* Write the new copy first, if successful, then erase the old copy */
629 if (lseek(fd, write_offset, SEEK_SET) < 0) {
630 SLOGE("Cannot seek to write persistent data");
631 goto err2;
632 }
633 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
634 (int) crypt_ftr.persist_data_size) {
635 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
636 SLOGE("Cannot seek to erase previous persistent data");
637 goto err2;
638 }
639 fsync(fd);
640 memset(pdata, 0, crypt_ftr.persist_data_size);
641 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
642 (int) crypt_ftr.persist_data_size) {
643 SLOGE("Cannot write to erase previous persistent data");
644 goto err2;
645 }
646 fsync(fd);
647 } else {
648 SLOGE("Cannot write to save persistent data");
649 goto err2;
650 }
651
652 /* Success */
653 free(pdata);
654 close(fd);
655 return 0;
656
657err2:
658 free(pdata);
659err:
660 close(fd);
661 return -1;
662}
663
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800664/* Convert a binary key of specified length into an ascii hex string equivalent,
665 * without the leading 0x and with null termination
666 */
667void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
668 char *master_key_ascii)
669{
670 unsigned int i, a;
671 unsigned char nibble;
672
673 for (i=0, a=0; i<keysize; i++, a+=2) {
674 /* For each byte, write out two ascii hex digits */
675 nibble = (master_key[i] >> 4) & 0xf;
676 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
677
678 nibble = master_key[i] & 0xf;
679 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
680 }
681
682 /* Add the null termination */
683 master_key_ascii[a] = '\0';
684
685}
686
Ken Sumralldb5e0262013-02-05 17:39:48 -0800687static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
688 char *real_blk_name, const char *name, int fd,
689 char *extra_params)
690{
691 char buffer[DM_CRYPT_BUF_SIZE];
692 struct dm_ioctl *io;
693 struct dm_target_spec *tgt;
694 char *crypt_params;
695 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
696 int i;
697
698 io = (struct dm_ioctl *) buffer;
699
700 /* Load the mapping table for this device */
701 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
702
703 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
704 io->target_count = 1;
705 tgt->status = 0;
706 tgt->sector_start = 0;
707 tgt->length = crypt_ftr->fs_size;
708 strcpy(tgt->target_type, "crypt");
709
710 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
711 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
712 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
713 master_key_ascii, real_blk_name, extra_params);
714 crypt_params += strlen(crypt_params) + 1;
715 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
716 tgt->next = crypt_params - buffer;
717
718 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
719 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
720 break;
721 }
722 usleep(500000);
723 }
724
725 if (i == TABLE_LOAD_RETRIES) {
726 /* We failed to load the table, return an error */
727 return -1;
728 } else {
729 return i + 1;
730 }
731}
732
733
734static int get_dm_crypt_version(int fd, const char *name, int *version)
735{
736 char buffer[DM_CRYPT_BUF_SIZE];
737 struct dm_ioctl *io;
738 struct dm_target_versions *v;
739 int i;
740
741 io = (struct dm_ioctl *) buffer;
742
743 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
744
745 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
746 return -1;
747 }
748
749 /* Iterate over the returned versions, looking for name of "crypt".
750 * When found, get and return the version.
751 */
752 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
753 while (v->next) {
754 if (! strcmp(v->name, "crypt")) {
755 /* We found the crypt driver, return the version, and get out */
756 version[0] = v->version[0];
757 version[1] = v->version[1];
758 version[2] = v->version[2];
759 return 0;
760 }
761 v = (struct dm_target_versions *)(((char *)v) + v->next);
762 }
763
764 return -1;
765}
766
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800767static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -0700768 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800769{
770 char buffer[DM_CRYPT_BUF_SIZE];
771 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
772 char *crypt_params;
773 struct dm_ioctl *io;
774 struct dm_target_spec *tgt;
775 unsigned int minor;
776 int fd;
Ken Sumralle919efe2012-09-29 17:07:41 -0700777 int i;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800778 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800779 int version[3];
780 char *extra_params;
781 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800782
783 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
784 SLOGE("Cannot open device-mapper\n");
785 goto errout;
786 }
787
788 io = (struct dm_ioctl *) buffer;
789
790 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
791 if (ioctl(fd, DM_DEV_CREATE, io)) {
792 SLOGE("Cannot create dm-crypt device\n");
793 goto errout;
794 }
795
796 /* Get the device status, in particular, the name of it's device file */
797 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
798 if (ioctl(fd, DM_DEV_STATUS, io)) {
799 SLOGE("Cannot retrieve dm-crypt device status\n");
800 goto errout;
801 }
802 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
803 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
804
Ken Sumralldb5e0262013-02-05 17:39:48 -0800805 extra_params = "";
806 if (! get_dm_crypt_version(fd, name, version)) {
807 /* Support for allow_discards was added in version 1.11.0 */
808 if ((version[0] >= 2) ||
809 ((version[0] == 1) && (version[1] >= 11))) {
810 extra_params = "1 allow_discards";
811 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
812 }
Ken Sumralle919efe2012-09-29 17:07:41 -0700813 }
814
Ken Sumralldb5e0262013-02-05 17:39:48 -0800815 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
816 fd, extra_params);
817 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800818 SLOGE("Cannot load dm-crypt mapping table.\n");
819 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800820 } else if (load_count > 1) {
821 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800822 }
823
824 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -0800825 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800826
827 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
828 SLOGE("Cannot resume the dm-crypt device\n");
829 goto errout;
830 }
831
832 /* We made it here with no errors. Woot! */
833 retval = 0;
834
835errout:
836 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
837
838 return retval;
839}
840
Ken Sumrall29d8da82011-05-18 17:20:07 -0700841static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800842{
843 int fd;
844 char buffer[DM_CRYPT_BUF_SIZE];
845 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800846 int retval = -1;
847
848 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
849 SLOGE("Cannot open device-mapper\n");
850 goto errout;
851 }
852
853 io = (struct dm_ioctl *) buffer;
854
855 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
856 if (ioctl(fd, DM_DEV_REMOVE, io)) {
857 SLOGE("Cannot remove dm-crypt device\n");
858 goto errout;
859 }
860
861 /* We made it here with no errors. Woot! */
862 retval = 0;
863
864errout:
865 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
866
867 return retval;
868
869}
870
Kenny Rootc4c70f12013-06-14 12:11:38 -0700871static void pbkdf2(char *passwd, unsigned char *salt, unsigned char *ikey, void *params) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800872 /* Turn the password into a key and IV that can decrypt the master key */
Ken Sumralle8744072011-01-18 22:01:55 -0800873 PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800874 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800875}
876
Kenny Rootc4c70f12013-06-14 12:11:38 -0700877static void scrypt(char *passwd, unsigned char *salt, unsigned char *ikey, void *params) {
878 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
879
880 int N = 1 << ftr->N_factor;
881 int r = 1 << ftr->r_factor;
882 int p = 1 << ftr->p_factor;
883
884 /* Turn the password into a key and IV that can decrypt the master key */
885 crypto_scrypt((unsigned char *) passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
886 KEY_LEN_BYTES + IV_LEN_BYTES);
887}
888
Ken Sumralle8744072011-01-18 22:01:55 -0800889static int encrypt_master_key(char *passwd, unsigned char *salt,
890 unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700891 unsigned char *encrypted_master_key,
892 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800893{
894 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
895 EVP_CIPHER_CTX e_ctx;
896 int encrypted_len, final_len;
897
898 /* Turn the password into a key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700899 get_device_scrypt_params(crypt_ftr);
900 scrypt(passwd, salt, ikey, crypt_ftr);
901
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800902 /* Initialize the decryption engine */
903 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
904 SLOGE("EVP_EncryptInit failed\n");
905 return -1;
906 }
907 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800908
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800909 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800910 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
911 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800912 SLOGE("EVP_EncryptUpdate failed\n");
913 return -1;
914 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800915 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800916 SLOGE("EVP_EncryptFinal failed\n");
917 return -1;
918 }
919
920 if (encrypted_len + final_len != KEY_LEN_BYTES) {
921 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
922 return -1;
923 } else {
924 return 0;
925 }
926}
927
JP Abgrall7bdfa522013-11-15 13:42:56 -0800928static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
Ken Sumralle8744072011-01-18 22:01:55 -0800929 unsigned char *encrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700930 unsigned char *decrypted_master_key,
931 kdf_func kdf, void *kdf_params)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800932{
933 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 -0800934 EVP_CIPHER_CTX d_ctx;
935 int decrypted_len, final_len;
936
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800937 /* Turn the password into a key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700938 kdf(passwd, salt, ikey, kdf_params);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800939
940 /* Initialize the decryption engine */
941 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
942 return -1;
943 }
944 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
945 /* Decrypt the master key */
946 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
947 encrypted_master_key, KEY_LEN_BYTES)) {
948 return -1;
949 }
950 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
951 return -1;
952 }
953
954 if (decrypted_len + final_len != KEY_LEN_BYTES) {
955 return -1;
956 } else {
957 return 0;
958 }
959}
960
Kenny Rootc4c70f12013-06-14 12:11:38 -0700961static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800962{
Kenny Rootc4c70f12013-06-14 12:11:38 -0700963 if (ftr->kdf_type == KDF_SCRYPT) {
964 *kdf = scrypt;
965 *kdf_params = ftr;
966 } else {
967 *kdf = pbkdf2;
968 *kdf_params = NULL;
969 }
970}
971
JP Abgrall7bdfa522013-11-15 13:42:56 -0800972static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700973 struct crypt_mnt_ftr *crypt_ftr)
974{
975 kdf_func kdf;
976 void *kdf_params;
977 int ret;
978
979 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
JP Abgrall7bdfa522013-11-15 13:42:56 -0800980 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, decrypted_master_key, kdf,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700981 kdf_params);
982 if (ret != 0) {
983 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -0700984 }
985
986 return ret;
987}
988
989static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
990 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800991 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -0800992 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800993 EVP_CIPHER_CTX e_ctx;
994 int encrypted_len, final_len;
995
996 /* Get some random bits for a key */
997 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -0800998 read(fd, key_buf, sizeof(key_buf));
999 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001000 close(fd);
1001
1002 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001003 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001004}
1005
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001006static int wait_and_unmount(char *mountpoint)
1007{
1008 int i, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001009#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001010
1011 /* Now umount the tmpfs filesystem */
1012 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
1013 if (umount(mountpoint)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001014 if (errno == EINVAL) {
1015 /* EINVAL is returned if the directory is not a mountpoint,
1016 * i.e. there is no filesystem mounted there. So just get out.
1017 */
1018 break;
1019 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001020 sleep(1);
1021 i++;
1022 } else {
1023 break;
1024 }
1025 }
1026
1027 if (i < WAIT_UNMOUNT_COUNT) {
1028 SLOGD("unmounting %s succeeded\n", mountpoint);
1029 rc = 0;
1030 } else {
1031 SLOGE("unmounting %s failed\n", mountpoint);
1032 rc = -1;
1033 }
1034
1035 return rc;
1036}
1037
Ken Sumrallc5872692013-05-14 15:26:31 -07001038#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001039static int prep_data_fs(void)
1040{
1041 int i;
1042
1043 /* Do the prep of the /data filesystem */
1044 property_set("vold.post_fs_data_done", "0");
1045 property_set("vold.decrypt", "trigger_post_fs_data");
1046 SLOGD("Just triggered post_fs_data\n");
1047
Ken Sumrallc5872692013-05-14 15:26:31 -07001048 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001049 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001050 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001051
1052 property_get("vold.post_fs_data_done", p, "0");
1053 if (*p == '1') {
1054 break;
1055 } else {
1056 usleep(250000);
1057 }
1058 }
1059 if (i == DATA_PREP_TIMEOUT) {
1060 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001061 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001062 return -1;
1063 } else {
1064 SLOGD("post_fs_data done\n");
1065 return 0;
1066 }
1067}
1068
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001069int cryptfs_restart(void)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001070{
1071 char fs_type[32];
1072 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001073 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001074 char fs_options[256];
1075 unsigned long mnt_flags;
1076 struct stat statbuf;
1077 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001078 static int restart_successful = 0;
1079
1080 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001081 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001082 SLOGE("Encrypted filesystem not validated, aborting");
1083 return -1;
1084 }
1085
1086 if (restart_successful) {
1087 SLOGE("System already restarted with encrypted disk, aborting");
1088 return -1;
1089 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001090
1091 /* Here is where we shut down the framework. The init scripts
1092 * start all services in one of three classes: core, main or late_start.
1093 * On boot, we start core and main. Now, we stop main, but not core,
1094 * as core includes vold and a few other really important things that
1095 * we need to keep running. Once main has stopped, we should be able
1096 * to umount the tmpfs /data, then mount the encrypted /data.
1097 * We then restart the class main, and also the class late_start.
1098 * At the moment, I've only put a few things in late_start that I know
1099 * are not needed to bring up the framework, and that also cause problems
1100 * with unmounting the tmpfs /data, but I hope to add add more services
1101 * to the late_start class as we optimize this to decrease the delay
1102 * till the user is asked for the password to the filesystem.
1103 */
1104
1105 /* The init files are setup to stop the class main when vold.decrypt is
1106 * set to trigger_reset_main.
1107 */
1108 property_set("vold.decrypt", "trigger_reset_main");
1109 SLOGD("Just asked init to shut down class main\n");
1110
Ken Sumrall92736ef2012-10-17 20:57:14 -07001111 /* Ugh, shutting down the framework is not synchronous, so until it
1112 * can be fixed, this horrible hack will wait a moment for it all to
1113 * shut down before proceeding. Without it, some devices cannot
1114 * restart the graphics services.
1115 */
1116 sleep(2);
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001117
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001118 /* Now that the framework is shutdown, we should be able to umount()
1119 * the tmpfs filesystem, and mount the real one.
1120 */
1121
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001122 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1123 if (strlen(crypto_blkdev) == 0) {
1124 SLOGE("fs_crypto_blkdev not set\n");
1125 return -1;
1126 }
1127
Ken Sumralle5032c42012-04-01 23:58:44 -07001128 if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001129 /* If ro.crypto.readonly is set to 1, mount the decrypted
1130 * filesystem readonly. This is used when /data is mounted by
1131 * recovery mode.
1132 */
1133 char ro_prop[PROPERTY_VALUE_MAX];
1134 property_get("ro.crypto.readonly", ro_prop, "");
1135 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1136 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1137 rec->flags |= MS_RDONLY;
1138 }
1139
Ken Sumralle5032c42012-04-01 23:58:44 -07001140 /* If that succeeded, then mount the decrypted filesystem */
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001141 fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001142
Ken Sumralle5032c42012-04-01 23:58:44 -07001143 property_set("vold.decrypt", "trigger_load_persist_props");
1144 /* Create necessary paths on /data */
1145 if (prep_data_fs()) {
1146 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001147 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001148
1149 /* startup service classes main and late_start */
1150 property_set("vold.decrypt", "trigger_restart_framework");
1151 SLOGD("Just triggered restart_framework\n");
1152
1153 /* Give it a few moments to get started */
1154 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001155 }
1156
Ken Sumrall0cc16632011-01-18 20:32:26 -08001157 if (rc == 0) {
1158 restart_successful = 1;
1159 }
1160
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001161 return rc;
1162}
1163
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001164static int do_crypto_complete(char *mount_point)
1165{
1166 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001167 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001168 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001169
1170 property_get("ro.crypto.state", encrypted_state, "");
1171 if (strcmp(encrypted_state, "encrypted") ) {
1172 SLOGE("not running with encryption, aborting");
1173 return 1;
1174 }
1175
Ken Sumrall160b4d62013-04-22 12:15:39 -07001176 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001177 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001178
Ken Sumralle1a45852011-12-14 21:24:27 -08001179 /*
1180 * Only report this error if key_loc is a file and it exists.
1181 * If the device was never encrypted, and /data is not mountable for
1182 * some reason, returning 1 should prevent the UI from presenting the
1183 * a "enter password" screen, or worse, a "press button to wipe the
1184 * device" screen.
1185 */
1186 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1187 SLOGE("master key file does not exist, aborting");
1188 return 1;
1189 } else {
1190 SLOGE("Error getting crypt footer and key\n");
1191 return -1;
1192 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001193 }
1194
1195 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1196 SLOGE("Encryption process didn't finish successfully\n");
1197 return -2; /* -2 is the clue to the UI that there is no usable data on the disk,
1198 * and give the user an option to wipe the disk */
1199 }
1200
1201 /* We passed the test! We shall diminish, and return to the west */
1202 return 0;
1203}
1204
Ken Sumrall29d8da82011-05-18 17:20:07 -07001205static int test_mount_encrypted_fs(char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001206{
1207 struct crypt_mnt_ftr crypt_ftr;
1208 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001209 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001210 char crypto_blkdev[MAXPATHLEN];
1211 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001212 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001213 unsigned int orig_failed_decrypt_count;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001214 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001215 int rc;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001216 kdf_func kdf;
1217 void *kdf_params;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001218
Ken Sumrall0cc16632011-01-18 20:32:26 -08001219 property_get("ro.crypto.state", encrypted_state, "");
Jason parks70a4b3f2011-01-28 10:10:47 -06001220 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001221 SLOGE("encrypted fs already validated or not running with encryption, aborting");
1222 return -1;
1223 }
1224
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001225 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001226
Ken Sumrall160b4d62013-04-22 12:15:39 -07001227 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001228 SLOGE("Error getting crypt footer and key\n");
1229 return -1;
1230 }
Ken Sumralld33d4172011-02-01 00:49:13 -08001231
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001232 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr.fs_size);
1233 orig_failed_decrypt_count = crypt_ftr.failed_decrypt_count;
1234
1235 if (! (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001236 if (decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr)) {
1237 SLOGE("Failed to decrypt master key\n");
1238 return -1;
1239 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001240 }
1241
1242 if (create_crypto_blk_dev(&crypt_ftr, decrypted_master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -07001243 real_blkdev, crypto_blkdev, label)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001244 SLOGE("Error creating decrypted block device\n");
1245 return -1;
1246 }
1247
Alex Klyubin707795a2013-05-10 15:17:07 -07001248 /* If init detects an encrypted filesystem, it writes a file for each such
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001249 * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
1250 * files and passes that data to me */
1251 /* Create a tmp mount point to try mounting the decryptd fs
1252 * Since we're here, the mount_point should be a tmpfs filesystem, so make
1253 * a directory in it to test mount the decrypted filesystem.
1254 */
1255 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1256 mkdir(tmp_mount_point, 0755);
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001257 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001258 SLOGE("Error temp mounting decrypted block device\n");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001259 delete_crypto_blk_dev(label);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001260 crypt_ftr.failed_decrypt_count++;
1261 } else {
1262 /* Success, so just umount and we'll mount it properly when we restart
1263 * the framework.
1264 */
1265 umount(tmp_mount_point);
1266 crypt_ftr.failed_decrypt_count = 0;
1267 }
1268
1269 if (orig_failed_decrypt_count != crypt_ftr.failed_decrypt_count) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001270 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001271 }
1272
1273 if (crypt_ftr.failed_decrypt_count) {
1274 /* We failed to mount the device, so return an error */
1275 rc = crypt_ftr.failed_decrypt_count;
1276
1277 } else {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001278 /* Woot! Success! Save the name of the crypto block device
1279 * so we can mount it when restarting the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001280 */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001281 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001282
1283 /* Also save a the master key so we can reencrypted the key
1284 * the key when we want to change the password on it.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001285 */
Jason parks70a4b3f2011-01-28 10:10:47 -06001286 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001287 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001288 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001289 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001290 rc = 0;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001291 /*
1292 * Upgrade if we're not using the latest KDF.
1293 */
1294 if (crypt_ftr.kdf_type != KDF_SCRYPT) {
1295 crypt_ftr.kdf_type = KDF_SCRYPT;
1296 rc = encrypt_master_key(passwd, crypt_ftr.salt, saved_master_key, crypt_ftr.master_key,
1297 &crypt_ftr);
1298 if (!rc) {
1299 rc = put_crypt_ftr_and_key(&crypt_ftr);
1300 }
1301 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1302 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001303 }
1304
1305 return rc;
1306}
1307
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001308/* Called by vold when it wants to undo the crypto mapping of a volume it
1309 * manages. This is usually in response to a factory reset, when we want
1310 * to undo the crypto mapping so the volume is formatted in the clear.
1311 */
1312int cryptfs_revert_volume(const char *label)
1313{
1314 return delete_crypto_blk_dev((char *)label);
1315}
1316
Ken Sumrall29d8da82011-05-18 17:20:07 -07001317/*
1318 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1319 * Setup a dm-crypt mapping, use the saved master key from
1320 * setting up the /data mapping, and return the new device path.
1321 */
1322int cryptfs_setup_volume(const char *label, int major, int minor,
1323 char *crypto_sys_path, unsigned int max_path,
1324 int *new_major, int *new_minor)
1325{
1326 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1327 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001328 struct stat statbuf;
1329 int nr_sec, fd;
1330
1331 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1332
Ken Sumrall160b4d62013-04-22 12:15:39 -07001333 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001334
1335 /* Update the fs_size field to be the size of the volume */
1336 fd = open(real_blkdev, O_RDONLY);
1337 nr_sec = get_blkdev_size(fd);
1338 close(fd);
1339 if (nr_sec == 0) {
1340 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1341 return -1;
1342 }
1343
1344 sd_crypt_ftr.fs_size = nr_sec;
1345 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1346 crypto_blkdev, label);
1347
1348 stat(crypto_blkdev, &statbuf);
1349 *new_major = MAJOR(statbuf.st_rdev);
1350 *new_minor = MINOR(statbuf.st_rdev);
1351
1352 /* Create path to sys entry for this block device */
1353 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1354
1355 return 0;
1356}
1357
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001358int cryptfs_crypto_complete(void)
1359{
1360 return do_crypto_complete("/data");
1361}
1362
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001363int cryptfs_check_passwd(char *passwd)
1364{
1365 int rc = -1;
1366
Ken Sumrall29d8da82011-05-18 17:20:07 -07001367 rc = test_mount_encrypted_fs(passwd, DATA_MNT_POINT, "userdata");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001368
1369 return rc;
1370}
1371
Ken Sumrall3ad90722011-10-04 20:38:29 -07001372int cryptfs_verify_passwd(char *passwd)
1373{
1374 struct crypt_mnt_ftr crypt_ftr;
1375 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001376 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001377 char encrypted_state[PROPERTY_VALUE_MAX];
1378 int rc;
1379
1380 property_get("ro.crypto.state", encrypted_state, "");
1381 if (strcmp(encrypted_state, "encrypted") ) {
1382 SLOGE("device not encrypted, aborting");
1383 return -2;
1384 }
1385
1386 if (!master_key_saved) {
1387 SLOGE("encrypted fs not yet mounted, aborting");
1388 return -1;
1389 }
1390
1391 if (!saved_mount_point) {
1392 SLOGE("encrypted fs failed to save mount point, aborting");
1393 return -1;
1394 }
1395
Ken Sumrall160b4d62013-04-22 12:15:39 -07001396 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001397 SLOGE("Error getting crypt footer and key\n");
1398 return -1;
1399 }
1400
1401 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1402 /* If the device has no password, then just say the password is valid */
1403 rc = 0;
1404 } else {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001405 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001406 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1407 /* They match, the password is correct */
1408 rc = 0;
1409 } else {
1410 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1411 sleep(1);
1412 rc = 1;
1413 }
1414 }
1415
1416 return rc;
1417}
1418
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001419/* Initialize a crypt_mnt_ftr structure. The keysize is
1420 * defaulted to 16 bytes, and the filesystem size to 0.
1421 * Presumably, at a minimum, the caller will update the
1422 * filesystem size and crypto_type_name after calling this function.
1423 */
1424static void cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
1425{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001426 off64_t off;
1427
1428 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001429 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001430 ftr->major_version = CURRENT_MAJOR_VERSION;
1431 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001432 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001433 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001434
Kenny Rootc4c70f12013-06-14 12:11:38 -07001435 ftr->kdf_type = KDF_SCRYPT;
1436 get_device_scrypt_params(ftr);
1437
Ken Sumrall160b4d62013-04-22 12:15:39 -07001438 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1439 if (get_crypt_ftr_info(NULL, &off) == 0) {
1440 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1441 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1442 ftr->persist_data_size;
1443 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001444}
1445
Ken Sumrall29d8da82011-05-18 17:20:07 -07001446static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001447{
Ken Sumralle550f782013-08-20 13:48:23 -07001448 const char *args[10];
1449 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1450 int num_args;
1451 int status;
1452 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001453 int rc = -1;
1454
Ken Sumrall29d8da82011-05-18 17:20:07 -07001455 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001456 args[0] = "/system/bin/make_ext4fs";
1457 args[1] = "-a";
1458 args[2] = "/data";
1459 args[3] = "-l";
1460 snprintf(size_str, sizeof(size_str), "%lld", size * 512);
1461 args[4] = size_str;
1462 args[5] = crypto_blkdev;
1463 num_args = 6;
1464 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1465 args[0], args[1], args[2], args[3], args[4], args[5]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001466 } else if (type== FAT_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001467 args[0] = "/system/bin/newfs_msdos";
1468 args[1] = "-F";
1469 args[2] = "32";
1470 args[3] = "-O";
1471 args[4] = "android";
1472 args[5] = "-c";
1473 args[6] = "8";
1474 args[7] = "-s";
1475 snprintf(size_str, sizeof(size_str), "%lld", size);
1476 args[8] = size_str;
1477 args[9] = crypto_blkdev;
1478 num_args = 10;
1479 SLOGI("Making empty filesystem with command %s %s %s %s %s %s %s %s %s %s\n",
1480 args[0], args[1], args[2], args[3], args[4], args[5],
1481 args[6], args[7], args[8], args[9]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001482 } else {
1483 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1484 return -1;
1485 }
1486
Ken Sumralle550f782013-08-20 13:48:23 -07001487 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1488
1489 if (tmp != 0) {
1490 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001491 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07001492 if (WIFEXITED(status)) {
1493 if (WEXITSTATUS(status)) {
1494 SLOGE("Error creating filesystem on %s, exit status %d ",
1495 crypto_blkdev, WEXITSTATUS(status));
1496 } else {
1497 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
1498 rc = 0;
1499 }
1500 } else {
1501 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
1502 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001503 }
1504
1505 return rc;
1506}
1507
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001508#define CRYPT_INPLACE_BUFSIZE 4096
1509#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / 512)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001510
1511/* aligned 32K writes tends to make flash happy.
1512 * SD card association recommends it.
1513 */
1514#define BLOCKS_AT_A_TIME 8
1515
1516struct encryptGroupsData
1517{
1518 int realfd;
1519 int cryptofd;
1520 off64_t numblocks;
1521 off64_t one_pct, cur_pct, new_pct;
1522 off64_t blocks_already_done, tot_numblocks;
1523 char* real_blkdev, * crypto_blkdev;
1524 int count;
1525 off64_t offset;
1526 char* buffer;
1527};
1528
1529static void update_progress(struct encryptGroupsData* data)
1530{
1531 data->blocks_already_done++;
1532 data->new_pct = data->blocks_already_done / data->one_pct;
1533 if (data->new_pct > data->cur_pct) {
1534 char buf[8];
1535 data->cur_pct = data->new_pct;
1536 snprintf(buf, sizeof(buf), "%lld", data->cur_pct);
1537 property_set("vold.encrypt_progress", buf);
1538 }
1539}
1540
1541static int flush_outstanding_data(struct encryptGroupsData* data)
1542{
1543 if (data->count == 0) {
1544 return 0;
1545 }
1546
1547 SLOGV("Copying %d blocks at offset %llx", data->count, data->offset);
1548
1549 if (pread64(data->realfd, data->buffer,
1550 info.block_size * data->count, data->offset)
1551 <= 0) {
1552 SLOGE("Error reading real_blkdev %s for inplace encrypt",
1553 data->real_blkdev);
1554 return -1;
1555 }
1556
1557 if (pwrite64(data->cryptofd, data->buffer,
1558 info.block_size * data->count, data->offset)
1559 <= 0) {
1560 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
1561 data->crypto_blkdev);
1562 return -1;
1563 }
1564
1565 data->count = 0;
1566 return 0;
1567}
1568
1569static int encrypt_groups(struct encryptGroupsData* data)
1570{
1571 unsigned int i;
1572 u8 *block_bitmap = 0;
1573 unsigned int block;
1574 off64_t ret;
1575 int rc = -1;
1576
1577 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
1578 if (!data->buffer) {
1579 SLOGE("Failed to allocate crypto buffer");
1580 goto errout;
1581 }
1582
1583 block_bitmap = malloc(info.block_size);
1584 if (!block_bitmap) {
1585 SLOGE("failed to allocate block bitmap");
1586 goto errout;
1587 }
1588
1589 for (i = 0; i < aux_info.groups; ++i) {
1590 SLOGI("Encrypting group %d", i);
1591
1592 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
1593 u32 block_count = min(info.blocks_per_group,
1594 aux_info.len_blocks - first_block);
1595
1596 off64_t offset = (u64)info.block_size
1597 * aux_info.bg_desc[i].bg_block_bitmap;
1598
1599 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
1600 if (ret != (int)info.block_size) {
1601 SLOGE("failed to read all of block group bitmap %d", i);
1602 goto errout;
1603 }
1604
1605 offset = (u64)info.block_size * first_block;
1606
1607 data->count = 0;
1608
1609 for (block = 0; block < block_count; block++) {
1610 update_progress(data);
1611 if (bitmap_get_bit(block_bitmap, block)) {
1612 if (data->count == 0) {
1613 data->offset = offset;
1614 }
1615 data->count++;
1616 } else {
1617 if (flush_outstanding_data(data)) {
1618 goto errout;
1619 }
1620 }
1621
1622 offset += info.block_size;
1623
1624 /* Write data if we are aligned or buffer size reached */
1625 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
1626 || data->count == BLOCKS_AT_A_TIME) {
1627 if (flush_outstanding_data(data)) {
1628 goto errout;
1629 }
1630 }
1631 }
1632 if (flush_outstanding_data(data)) {
1633 goto errout;
1634 }
1635 }
1636
1637 rc = 0;
1638
1639errout:
1640 free(data->buffer);
1641 free(block_bitmap);
1642 return rc;
1643}
1644
1645static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
1646 char *real_blkdev,
1647 off64_t size,
1648 off64_t *size_already_done,
1649 off64_t tot_size)
1650{
1651 int i;
1652 struct encryptGroupsData data;
1653 int rc = -1;
1654
1655 memset(&data, 0, sizeof(data));
1656 data.real_blkdev = real_blkdev;
1657 data.crypto_blkdev = crypto_blkdev;
1658
1659 if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
1660 SLOGE("Error opening real_blkdev %s for inplace encrypt\n",
1661 real_blkdev);
1662 goto errout;
1663 }
1664
1665 if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
1666 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n",
1667 crypto_blkdev);
1668 goto errout;
1669 }
1670
1671 if (setjmp(setjmp_env)) {
1672 SLOGE("Reading extent caused an exception");
1673 goto errout;
1674 }
1675
1676 if (read_ext(data.realfd, 0) != 0) {
1677 SLOGE("Failed to read extent");
1678 goto errout;
1679 }
1680
1681 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
1682 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
1683 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
1684
1685 SLOGI("Encrypting filesystem in place...");
1686
1687 data.one_pct = data.tot_numblocks / 100;
1688 data.cur_pct = 0;
1689
1690 rc = encrypt_groups(&data);
1691 if (rc) {
1692 SLOGE("Error encrypting groups");
1693 goto errout;
1694 }
1695
1696 *size_already_done += size;
1697 rc = 0;
1698
1699errout:
1700 close(data.realfd);
1701 close(data.cryptofd);
1702
1703 return rc;
1704}
1705
1706static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
1707 off64_t size, off64_t *size_already_done,
1708 off64_t tot_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001709{
1710 int realfd, cryptofd;
1711 char *buf[CRYPT_INPLACE_BUFSIZE];
1712 int rc = -1;
1713 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001714 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001715 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001716
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001717 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
1718 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
1719 return -1;
1720 }
1721
1722 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
1723 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1724 close(realfd);
1725 return -1;
1726 }
1727
1728 /* This is pretty much a simple loop of reading 4K, and writing 4K.
1729 * The size passed in is the number of 512 byte sectors in the filesystem.
1730 * So compute the number of whole 4K blocks we should read/write,
1731 * and the remainder.
1732 */
1733 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
1734 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001735 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
1736 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001737
1738 SLOGE("Encrypting filesystem in place...");
1739
Ken Sumrall29d8da82011-05-18 17:20:07 -07001740 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001741 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001742 /* process the majority of the filesystem in blocks */
1743 for (i=0; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001744 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001745 if (new_pct > cur_pct) {
1746 char buf[8];
1747
1748 cur_pct = new_pct;
1749 snprintf(buf, sizeof(buf), "%lld", cur_pct);
1750 property_set("vold.encrypt_progress", buf);
1751 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001752 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1753 SLOGE("Error reading real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1754 goto errout;
1755 }
1756 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1757 SLOGE("Error writing crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1758 goto errout;
1759 }
1760 }
1761
1762 /* Do any remaining sectors */
1763 for (i=0; i<remainder; i++) {
1764 if (unix_read(realfd, buf, 512) <= 0) {
1765 SLOGE("Error reading rival sectors from real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1766 goto errout;
1767 }
1768 if (unix_write(cryptofd, buf, 512) <= 0) {
1769 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1770 goto errout;
1771 }
1772 }
1773
Ken Sumrall29d8da82011-05-18 17:20:07 -07001774 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001775 rc = 0;
1776
1777errout:
1778 close(realfd);
1779 close(cryptofd);
1780
1781 return rc;
1782}
1783
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001784static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
1785 off64_t size, off64_t *size_already_done,
1786 off64_t tot_size)
1787{
1788 if (cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
1789 size, size_already_done, tot_size) == 0) {
1790 return 0;
1791 }
1792
1793 return cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
1794 size, size_already_done, tot_size);
1795}
1796
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001797#define CRYPTO_ENABLE_WIPE 1
1798#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001799
1800#define FRAMEWORK_BOOT_WAIT 60
1801
Ken Sumrall29d8da82011-05-18 17:20:07 -07001802static inline int should_encrypt(struct volume_info *volume)
1803{
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001804 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
Ken Sumrall29d8da82011-05-18 17:20:07 -07001805 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
1806}
1807
JP Abgrall502dc742013-11-01 13:06:20 -07001808int cryptfs_enable(char *howarg, char *passwd, int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001809{
1810 int how = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001811 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN], sd_crypto_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07001812 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001813 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07001814 int rc=-1, fd, i, ret;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001815 struct crypt_mnt_ftr crypt_ftr, sd_crypt_ftr;;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001816 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001817 char tmpfs_options[PROPERTY_VALUE_MAX];
1818 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001819 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07001820 char key_loc[PROPERTY_VALUE_MAX];
1821 char fuse_sdcard[PROPERTY_VALUE_MAX];
1822 char *sd_mnt_point;
1823 char sd_blk_dev[256] = { 0 };
1824 int num_vols;
1825 struct volume_info *vol_list = 0;
1826 off64_t cur_encryption_done=0, tot_encryption_size=0;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001827
1828 property_get("ro.crypto.state", encrypted_state, "");
JP Abgrall502dc742013-11-01 13:06:20 -07001829 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001830 SLOGE("Device is already running encrypted, aborting");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001831 goto error_unencrypted;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001832 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001833
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001834 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001835
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001836 if (!strcmp(howarg, "wipe")) {
1837 how = CRYPTO_ENABLE_WIPE;
1838 } else if (! strcmp(howarg, "inplace")) {
1839 how = CRYPTO_ENABLE_INPLACE;
1840 } else {
1841 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08001842 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001843 }
1844
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001845 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001846
Ken Sumrall3ed82362011-01-28 23:31:16 -08001847 /* Get the size of the real block device */
1848 fd = open(real_blkdev, O_RDONLY);
1849 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
1850 SLOGE("Cannot get size of block device %s\n", real_blkdev);
1851 goto error_unencrypted;
1852 }
1853 close(fd);
1854
1855 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001856 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001857 unsigned int fs_size_sec, max_fs_size_sec;
1858
1859 fs_size_sec = get_fs_size(real_blkdev);
1860 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1861
1862 if (fs_size_sec > max_fs_size_sec) {
1863 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
1864 goto error_unencrypted;
1865 }
1866 }
1867
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001868 /* Get a wakelock as this may take a while, and we don't want the
1869 * device to sleep on us. We'll grab a partial wakelock, and if the UI
1870 * wants to keep the screen on, it can grab a full wakelock.
1871 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001872 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001873 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
1874
Jeff Sharkey7382f812012-08-23 14:08:59 -07001875 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07001876 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07001877 if (!sd_mnt_point) {
1878 sd_mnt_point = getenv("EXTERNAL_STORAGE");
1879 }
1880 if (!sd_mnt_point) {
1881 sd_mnt_point = "/mnt/sdcard";
1882 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07001883
1884 num_vols=vold_getNumDirectVolumes();
1885 vol_list = malloc(sizeof(struct volume_info) * num_vols);
1886 vold_getDirectVolumeList(vol_list);
1887
1888 for (i=0; i<num_vols; i++) {
1889 if (should_encrypt(&vol_list[i])) {
1890 fd = open(vol_list[i].blk_dev, O_RDONLY);
1891 if ( (vol_list[i].size = get_blkdev_size(fd)) == 0) {
1892 SLOGE("Cannot get size of block device %s\n", vol_list[i].blk_dev);
1893 goto error_unencrypted;
1894 }
1895 close(fd);
1896
Ken Sumrall3b170052011-07-11 15:38:57 -07001897 ret=vold_disableVol(vol_list[i].label);
Ken Sumrall319b1042011-06-14 14:01:55 -07001898 if ((ret < 0) && (ret != UNMOUNT_NOT_MOUNTED_ERR)) {
1899 /* -2 is returned when the device exists but is not currently mounted.
1900 * ignore the error and continue. */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001901 SLOGE("Failed to unmount volume %s\n", vol_list[i].label);
1902 goto error_unencrypted;
1903 }
1904 }
1905 }
1906
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001907 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001908 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001909 */
1910 property_set("vold.decrypt", "trigger_shutdown_framework");
1911 SLOGD("Just asked init to shut down class main\n");
1912
Ken Sumrall425524d2012-06-14 20:55:28 -07001913 if (vold_unmountAllAsecs()) {
1914 /* Just report the error. If any are left mounted,
1915 * umounting /data below will fail and handle the error.
1916 */
1917 SLOGE("Error unmounting internal asecs");
1918 }
1919
Ken Sumrall29d8da82011-05-18 17:20:07 -07001920 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
1921 if (!strcmp(fuse_sdcard, "true")) {
1922 /* This is a device using the fuse layer to emulate the sdcard semantics
1923 * on top of the userdata partition. vold does not manage it, it is managed
1924 * by the sdcard service. The sdcard service was killed by the property trigger
1925 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
1926 * unlike the case for vold managed devices above.
1927 */
1928 if (wait_and_unmount(sd_mnt_point)) {
1929 goto error_shutting_down;
1930 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001931 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001932
1933 /* Now unmount the /data partition. */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001934 if (wait_and_unmount(DATA_MNT_POINT)) {
JP Abgrall502dc742013-11-01 13:06:20 -07001935 if (allow_reboot) {
1936 goto error_shutting_down;
1937 } else {
1938 goto error_unencrypted;
1939 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001940 }
1941
1942 /* Do extra work for a better UX when doing the long inplace encryption */
1943 if (how == CRYPTO_ENABLE_INPLACE) {
1944 /* Now that /data is unmounted, we need to mount a tmpfs
1945 * /data, set a property saying we're doing inplace encryption,
1946 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001947 */
Ken Sumralle5032c42012-04-01 23:58:44 -07001948 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001949 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001950 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001951 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08001952 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001953
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001954 /* restart the framework. */
1955 /* Create necessary paths on /data */
1956 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001957 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001958 }
1959
Ken Sumrall92736ef2012-10-17 20:57:14 -07001960 /* Ugh, shutting down the framework is not synchronous, so until it
1961 * can be fixed, this horrible hack will wait a moment for it all to
1962 * shut down before proceeding. Without it, some devices cannot
1963 * restart the graphics services.
1964 */
1965 sleep(2);
1966
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001967 /* startup service classes main and late_start */
1968 property_set("vold.decrypt", "trigger_restart_min_framework");
1969 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001970
Ken Sumrall7df84122011-01-18 14:04:08 -08001971 /* OK, the framework is restarted and will soon be showing a
1972 * progress bar. Time to setup an encrypted mapping, and
1973 * either write a new filesystem, or encrypt in place updating
1974 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001975 */
1976 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001977
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001978 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001979 /* Initialize a crypt_mnt_ftr for the partition */
1980 cryptfs_init_crypt_mnt_ftr(&crypt_ftr);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001981
Ken Sumrall29d8da82011-05-18 17:20:07 -07001982 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
1983 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1984 } else {
1985 crypt_ftr.fs_size = nr_sec;
1986 }
Ken Sumralld33d4172011-02-01 00:49:13 -08001987 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001988 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
1989
1990 /* Make an encrypted master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001991 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001992 SLOGE("Cannot create encrypted master key\n");
JP Abgrall502dc742013-11-01 13:06:20 -07001993 goto error_shutting_down;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001994 }
1995
1996 /* Write the key to the end of the partition */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001997 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001998
Ken Sumrall160b4d62013-04-22 12:15:39 -07001999 /* If any persistent data has been remembered, save it.
2000 * If none, create a valid empty table and save that.
2001 */
2002 if (!persist_data) {
2003 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
2004 if (pdata) {
2005 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2006 persist_data = pdata;
2007 }
2008 }
2009 if (persist_data) {
2010 save_persistent_data();
2011 }
2012
JP Abgrall7bdfa522013-11-15 13:42:56 -08002013 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002014 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
2015 "userdata");
2016
Ken Sumrall128626f2011-06-28 18:45:14 -07002017 /* The size of the userdata partition, and add in the vold volumes below */
2018 tot_encryption_size = crypt_ftr.fs_size;
2019
Ken Sumrall29d8da82011-05-18 17:20:07 -07002020 /* setup crypto mapping for all encryptable volumes handled by vold */
2021 for (i=0; i<num_vols; i++) {
2022 if (should_encrypt(&vol_list[i])) {
2023 vol_list[i].crypt_ftr = crypt_ftr; /* gotta love struct assign */
2024 vol_list[i].crypt_ftr.fs_size = vol_list[i].size;
2025 create_crypto_blk_dev(&vol_list[i].crypt_ftr, decrypted_master_key,
2026 vol_list[i].blk_dev, vol_list[i].crypto_blkdev,
2027 vol_list[i].label);
Ken Sumrall128626f2011-06-28 18:45:14 -07002028 tot_encryption_size += vol_list[i].size;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002029 }
2030 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002031
2032 if (how == CRYPTO_ENABLE_WIPE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002033 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr.fs_size, EXT4_FS);
2034 /* Encrypt all encryptable volumes handled by vold */
2035 if (!rc) {
2036 for (i=0; i<num_vols; i++) {
2037 if (should_encrypt(&vol_list[i])) {
2038 rc = cryptfs_enable_wipe(vol_list[i].crypto_blkdev,
2039 vol_list[i].crypt_ftr.fs_size, FAT_FS);
2040 }
2041 }
2042 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002043 } else if (how == CRYPTO_ENABLE_INPLACE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002044 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr.fs_size,
2045 &cur_encryption_done, tot_encryption_size);
2046 /* Encrypt all encryptable volumes handled by vold */
2047 if (!rc) {
2048 for (i=0; i<num_vols; i++) {
2049 if (should_encrypt(&vol_list[i])) {
2050 rc = cryptfs_enable_inplace(vol_list[i].crypto_blkdev,
2051 vol_list[i].blk_dev,
2052 vol_list[i].crypt_ftr.fs_size,
2053 &cur_encryption_done, tot_encryption_size);
2054 }
2055 }
2056 }
2057 if (!rc) {
2058 /* The inplace routine never actually sets the progress to 100%
2059 * due to the round down nature of integer division, so set it here */
2060 property_set("vold.encrypt_progress", "100");
2061 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002062 } else {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002063 /* Shouldn't happen */
2064 SLOGE("cryptfs_enable: internal error, unknown option\n");
JP Abgrall502dc742013-11-01 13:06:20 -07002065 goto error_shutting_down;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002066 }
2067
2068 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002069 delete_crypto_blk_dev("userdata");
2070 for (i=0; i<num_vols; i++) {
2071 if (should_encrypt(&vol_list[i])) {
2072 delete_crypto_blk_dev(vol_list[i].label);
2073 }
2074 }
2075
2076 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002077
2078 if (! rc) {
2079 /* Success */
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002080
Ken Sumralld33d4172011-02-01 00:49:13 -08002081 /* Clear the encryption in progres flag in the footer */
2082 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002083 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002084
Ken Sumrall29d8da82011-05-18 17:20:07 -07002085 sleep(2); /* Give the UI a chance to show 100% progress */
Ken Sumralladfba362013-06-04 16:37:52 -07002086 cryptfs_reboot(0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002087 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002088 char value[PROPERTY_VALUE_MAX];
2089
Ken Sumrall319369a2012-06-27 16:30:18 -07002090 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002091 if (!strcmp(value, "1")) {
2092 /* wipe data if encryption failed */
2093 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
2094 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07002095 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002096 if (fd >= 0) {
2097 write(fd, "--wipe_data", strlen("--wipe_data") + 1);
2098 close(fd);
2099 } else {
2100 SLOGE("could not open /cache/recovery/command\n");
2101 }
Ken Sumralladfba362013-06-04 16:37:52 -07002102 cryptfs_reboot(1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002103 } else {
2104 /* set property to trigger dialog */
2105 property_set("vold.encrypt_progress", "error_partially_encrypted");
2106 release_wake_lock(lockid);
2107 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002108 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002109 }
2110
Ken Sumrall3ed82362011-01-28 23:31:16 -08002111 /* hrm, the encrypt step claims success, but the reboot failed.
2112 * This should not happen.
2113 * Set the property and return. Hope the framework can deal with it.
2114 */
2115 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002116 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002117 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002118
2119error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07002120 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002121 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002122 if (lockid[0]) {
2123 release_wake_lock(lockid);
2124 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002125 return -1;
2126
2127error_shutting_down:
2128 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2129 * but the framework is stopped and not restarted to show the error, so it's up to
2130 * vold to restart the system.
2131 */
2132 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Ken Sumralladfba362013-06-04 16:37:52 -07002133 cryptfs_reboot(0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002134
2135 /* shouldn't get here */
2136 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07002137 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002138 if (lockid[0]) {
2139 release_wake_lock(lockid);
2140 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002141 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002142}
2143
Jason parks70a4b3f2011-01-28 10:10:47 -06002144int cryptfs_changepw(char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002145{
2146 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002147 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002148
2149 /* This is only allowed after we've successfully decrypted the master key */
Jason parks70a4b3f2011-01-28 10:10:47 -06002150 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002151 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002152 return -1;
2153 }
2154
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002155 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002156 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall57b63e62011-01-17 18:29:19 -08002157 SLOGE("Error getting crypt footer and key");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002158 return -1;
2159 }
2160
Kenny Rootc4c70f12013-06-14 12:11:38 -07002161 encrypt_master_key(newpw, crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002162
Jason parks70a4b3f2011-01-28 10:10:47 -06002163 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002164 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002165
2166 return 0;
2167}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002168
2169static int persist_get_key(char *fieldname, char *value)
2170{
2171 unsigned int i;
2172
2173 if (persist_data == NULL) {
2174 return -1;
2175 }
2176 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2177 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2178 /* We found it! */
2179 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2180 return 0;
2181 }
2182 }
2183
2184 return -1;
2185}
2186
2187static int persist_set_key(char *fieldname, char *value, int encrypted)
2188{
2189 unsigned int i;
2190 unsigned int num;
2191 struct crypt_mnt_ftr crypt_ftr;
2192 unsigned int max_persistent_entries;
2193 unsigned int dsize;
2194
2195 if (persist_data == NULL) {
2196 return -1;
2197 }
2198
2199 /* If encrypted, use the values from the crypt_ftr, otherwise
2200 * use the values for the current spec.
2201 */
2202 if (encrypted) {
2203 if(get_crypt_ftr_and_key(&crypt_ftr)) {
2204 return -1;
2205 }
2206 dsize = crypt_ftr.persist_data_size;
2207 } else {
2208 dsize = CRYPT_PERSIST_DATA_SIZE;
2209 }
2210 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2211 sizeof(struct crypt_persist_entry);
2212
2213 num = persist_data->persist_valid_entries;
2214
2215 for (i = 0; i < num; i++) {
2216 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2217 /* We found an existing entry, update it! */
2218 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2219 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2220 return 0;
2221 }
2222 }
2223
2224 /* We didn't find it, add it to the end, if there is room */
2225 if (persist_data->persist_valid_entries < max_persistent_entries) {
2226 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2227 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2228 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2229 persist_data->persist_valid_entries++;
2230 return 0;
2231 }
2232
2233 return -1;
2234}
2235
2236/* Return the value of the specified field. */
2237int cryptfs_getfield(char *fieldname, char *value, int len)
2238{
2239 char temp_value[PROPERTY_VALUE_MAX];
2240 char real_blkdev[MAXPATHLEN];
2241 /* 0 is success, 1 is not encrypted,
2242 * -1 is value not set, -2 is any other error
2243 */
2244 int rc = -2;
2245
2246 if (persist_data == NULL) {
2247 load_persistent_data();
2248 if (persist_data == NULL) {
2249 SLOGE("Getfield error, cannot load persistent data");
2250 goto out;
2251 }
2252 }
2253
2254 if (!persist_get_key(fieldname, temp_value)) {
2255 /* We found it, copy it to the caller's buffer and return */
2256 strlcpy(value, temp_value, len);
2257 rc = 0;
2258 } else {
2259 /* Sadness, it's not there. Return the error */
2260 rc = -1;
2261 }
2262
2263out:
2264 return rc;
2265}
2266
2267/* Set the value of the specified field. */
2268int cryptfs_setfield(char *fieldname, char *value)
2269{
2270 struct crypt_persist_data stored_pdata;
2271 struct crypt_persist_data *pdata_p;
2272 struct crypt_mnt_ftr crypt_ftr;
2273 char encrypted_state[PROPERTY_VALUE_MAX];
2274 /* 0 is success, -1 is an error */
2275 int rc = -1;
2276 int encrypted = 0;
2277
2278 if (persist_data == NULL) {
2279 load_persistent_data();
2280 if (persist_data == NULL) {
2281 SLOGE("Setfield error, cannot load persistent data");
2282 goto out;
2283 }
2284 }
2285
2286 property_get("ro.crypto.state", encrypted_state, "");
2287 if (!strcmp(encrypted_state, "encrypted") ) {
2288 encrypted = 1;
2289 }
2290
2291 if (persist_set_key(fieldname, value, encrypted)) {
2292 goto out;
2293 }
2294
2295 /* If we are running encrypted, save the persistent data now */
2296 if (encrypted) {
2297 if (save_persistent_data()) {
2298 SLOGE("Setfield error, cannot save persistent data");
2299 goto out;
2300 }
2301 }
2302
2303 rc = 0;
2304
2305out:
2306 return rc;
2307}