blob: 03d714eb4d5ec296ac37c3a751857e9c25284dd0 [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"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080052
53#define DM_CRYPT_BUF_SIZE 4096
Ken Sumrall8ddbe402011-01-17 15:26:29 -080054#define DATA_MNT_POINT "/data"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080055
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");
354 crypt_ftr->kdf_type = KDF_PBKDF2;
355 get_device_scrypt_params(crypt_ftr);
356 crypt_ftr->minor_version = 2;
357 }
358
Kenny Root7434b312013-06-14 11:29:53 -0700359 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
360 if (lseek64(fd, offset, SEEK_SET) == -1) {
361 SLOGE("Cannot seek to crypt footer\n");
362 return;
363 }
364 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700365 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700366}
367
368
369static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800370{
371 int fd;
372 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700373 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800374 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700375 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700376 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800377
Ken Sumrall160b4d62013-04-22 12:15:39 -0700378 if (get_crypt_ftr_info(&fname, &starting_off)) {
379 SLOGE("Unable to get crypt_ftr_info\n");
380 return -1;
381 }
382 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700383 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700384 return -1;
385 }
386 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700387 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700388 return -1;
389 }
390
391 /* Make sure it's 16 Kbytes in length */
392 fstat(fd, &statbuf);
393 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
394 SLOGE("footer file %s is not the expected size!\n", fname);
395 goto errout;
396 }
397
398 /* Seek to the start of the crypt footer */
399 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
400 SLOGE("Cannot seek to real block device footer\n");
401 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800402 }
403
404 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
405 SLOGE("Cannot read real block device footer\n");
406 goto errout;
407 }
408
409 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700410 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800411 goto errout;
412 }
413
Kenny Rootc96a5f82013-06-14 12:08:28 -0700414 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
415 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
416 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800417 goto errout;
418 }
419
Kenny Rootc96a5f82013-06-14 12:08:28 -0700420 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
421 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
422 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800423 }
424
Ken Sumrall160b4d62013-04-22 12:15:39 -0700425 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
426 * copy on disk before returning.
427 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700428 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700429 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800430 }
431
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800432 /* Success! */
433 rc = 0;
434
435errout:
436 close(fd);
437 return rc;
438}
439
Ken Sumrall160b4d62013-04-22 12:15:39 -0700440static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
441{
442 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
443 crypt_ftr->persist_data_offset[1]) {
444 SLOGE("Crypt_ftr persist data regions overlap");
445 return -1;
446 }
447
448 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
449 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
450 return -1;
451 }
452
453 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
454 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
455 CRYPT_FOOTER_OFFSET) {
456 SLOGE("Persistent data extends past crypto footer");
457 return -1;
458 }
459
460 return 0;
461}
462
463static int load_persistent_data(void)
464{
465 struct crypt_mnt_ftr crypt_ftr;
466 struct crypt_persist_data *pdata = NULL;
467 char encrypted_state[PROPERTY_VALUE_MAX];
468 char *fname;
469 int found = 0;
470 int fd;
471 int ret;
472 int i;
473
474 if (persist_data) {
475 /* Nothing to do, we've already loaded or initialized it */
476 return 0;
477 }
478
479
480 /* If not encrypted, just allocate an empty table and initialize it */
481 property_get("ro.crypto.state", encrypted_state, "");
482 if (strcmp(encrypted_state, "encrypted") ) {
483 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
484 if (pdata) {
485 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
486 persist_data = pdata;
487 return 0;
488 }
489 return -1;
490 }
491
492 if(get_crypt_ftr_and_key(&crypt_ftr)) {
493 return -1;
494 }
495
496 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
497 SLOGE("Crypt_ftr version doesn't support persistent data");
498 return -1;
499 }
500
501 if (get_crypt_ftr_info(&fname, NULL)) {
502 return -1;
503 }
504
505 ret = validate_persistent_data_storage(&crypt_ftr);
506 if (ret) {
507 return -1;
508 }
509
510 fd = open(fname, O_RDONLY);
511 if (fd < 0) {
512 SLOGE("Cannot open %s metadata file", fname);
513 return -1;
514 }
515
516 if (persist_data == NULL) {
517 pdata = malloc(crypt_ftr.persist_data_size);
518 if (pdata == NULL) {
519 SLOGE("Cannot allocate memory for persistent data");
520 goto err;
521 }
522 }
523
524 for (i = 0; i < 2; i++) {
525 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
526 SLOGE("Cannot seek to read persistent data on %s", fname);
527 goto err2;
528 }
529 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
530 SLOGE("Error reading persistent data on iteration %d", i);
531 goto err2;
532 }
533 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
534 found = 1;
535 break;
536 }
537 }
538
539 if (!found) {
540 SLOGI("Could not find valid persistent data, creating");
541 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
542 }
543
544 /* Success */
545 persist_data = pdata;
546 close(fd);
547 return 0;
548
549err2:
550 free(pdata);
551
552err:
553 close(fd);
554 return -1;
555}
556
557static int save_persistent_data(void)
558{
559 struct crypt_mnt_ftr crypt_ftr;
560 struct crypt_persist_data *pdata;
561 char *fname;
562 off64_t write_offset;
563 off64_t erase_offset;
564 int found = 0;
565 int fd;
566 int ret;
567
568 if (persist_data == NULL) {
569 SLOGE("No persistent data to save");
570 return -1;
571 }
572
573 if(get_crypt_ftr_and_key(&crypt_ftr)) {
574 return -1;
575 }
576
577 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
578 SLOGE("Crypt_ftr version doesn't support persistent data");
579 return -1;
580 }
581
582 ret = validate_persistent_data_storage(&crypt_ftr);
583 if (ret) {
584 return -1;
585 }
586
587 if (get_crypt_ftr_info(&fname, NULL)) {
588 return -1;
589 }
590
591 fd = open(fname, O_RDWR);
592 if (fd < 0) {
593 SLOGE("Cannot open %s metadata file", fname);
594 return -1;
595 }
596
597 pdata = malloc(crypt_ftr.persist_data_size);
598 if (pdata == NULL) {
599 SLOGE("Cannot allocate persistant data");
600 goto err;
601 }
602
603 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
604 SLOGE("Cannot seek to read persistent data on %s", fname);
605 goto err2;
606 }
607
608 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
609 SLOGE("Error reading persistent data before save");
610 goto err2;
611 }
612
613 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
614 /* The first copy is the curent valid copy, so write to
615 * the second copy and erase this one */
616 write_offset = crypt_ftr.persist_data_offset[1];
617 erase_offset = crypt_ftr.persist_data_offset[0];
618 } else {
619 /* The second copy must be the valid copy, so write to
620 * the first copy, and erase the second */
621 write_offset = crypt_ftr.persist_data_offset[0];
622 erase_offset = crypt_ftr.persist_data_offset[1];
623 }
624
625 /* Write the new copy first, if successful, then erase the old copy */
626 if (lseek(fd, write_offset, SEEK_SET) < 0) {
627 SLOGE("Cannot seek to write persistent data");
628 goto err2;
629 }
630 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
631 (int) crypt_ftr.persist_data_size) {
632 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
633 SLOGE("Cannot seek to erase previous persistent data");
634 goto err2;
635 }
636 fsync(fd);
637 memset(pdata, 0, crypt_ftr.persist_data_size);
638 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
639 (int) crypt_ftr.persist_data_size) {
640 SLOGE("Cannot write to erase previous persistent data");
641 goto err2;
642 }
643 fsync(fd);
644 } else {
645 SLOGE("Cannot write to save persistent data");
646 goto err2;
647 }
648
649 /* Success */
650 free(pdata);
651 close(fd);
652 return 0;
653
654err2:
655 free(pdata);
656err:
657 close(fd);
658 return -1;
659}
660
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800661/* Convert a binary key of specified length into an ascii hex string equivalent,
662 * without the leading 0x and with null termination
663 */
664void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
665 char *master_key_ascii)
666{
667 unsigned int i, a;
668 unsigned char nibble;
669
670 for (i=0, a=0; i<keysize; i++, a+=2) {
671 /* For each byte, write out two ascii hex digits */
672 nibble = (master_key[i] >> 4) & 0xf;
673 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
674
675 nibble = master_key[i] & 0xf;
676 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
677 }
678
679 /* Add the null termination */
680 master_key_ascii[a] = '\0';
681
682}
683
Ken Sumralldb5e0262013-02-05 17:39:48 -0800684static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
685 char *real_blk_name, const char *name, int fd,
686 char *extra_params)
687{
688 char buffer[DM_CRYPT_BUF_SIZE];
689 struct dm_ioctl *io;
690 struct dm_target_spec *tgt;
691 char *crypt_params;
692 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
693 int i;
694
695 io = (struct dm_ioctl *) buffer;
696
697 /* Load the mapping table for this device */
698 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
699
700 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
701 io->target_count = 1;
702 tgt->status = 0;
703 tgt->sector_start = 0;
704 tgt->length = crypt_ftr->fs_size;
705 strcpy(tgt->target_type, "crypt");
706
707 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
708 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
709 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
710 master_key_ascii, real_blk_name, extra_params);
711 crypt_params += strlen(crypt_params) + 1;
712 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
713 tgt->next = crypt_params - buffer;
714
715 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
716 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
717 break;
718 }
719 usleep(500000);
720 }
721
722 if (i == TABLE_LOAD_RETRIES) {
723 /* We failed to load the table, return an error */
724 return -1;
725 } else {
726 return i + 1;
727 }
728}
729
730
731static int get_dm_crypt_version(int fd, const char *name, int *version)
732{
733 char buffer[DM_CRYPT_BUF_SIZE];
734 struct dm_ioctl *io;
735 struct dm_target_versions *v;
736 int i;
737
738 io = (struct dm_ioctl *) buffer;
739
740 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
741
742 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
743 return -1;
744 }
745
746 /* Iterate over the returned versions, looking for name of "crypt".
747 * When found, get and return the version.
748 */
749 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
750 while (v->next) {
751 if (! strcmp(v->name, "crypt")) {
752 /* We found the crypt driver, return the version, and get out */
753 version[0] = v->version[0];
754 version[1] = v->version[1];
755 version[2] = v->version[2];
756 return 0;
757 }
758 v = (struct dm_target_versions *)(((char *)v) + v->next);
759 }
760
761 return -1;
762}
763
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800764static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -0700765 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800766{
767 char buffer[DM_CRYPT_BUF_SIZE];
768 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
769 char *crypt_params;
770 struct dm_ioctl *io;
771 struct dm_target_spec *tgt;
772 unsigned int minor;
773 int fd;
Ken Sumralle919efe2012-09-29 17:07:41 -0700774 int i;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800775 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800776 int version[3];
777 char *extra_params;
778 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800779
780 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
781 SLOGE("Cannot open device-mapper\n");
782 goto errout;
783 }
784
785 io = (struct dm_ioctl *) buffer;
786
787 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
788 if (ioctl(fd, DM_DEV_CREATE, io)) {
789 SLOGE("Cannot create dm-crypt device\n");
790 goto errout;
791 }
792
793 /* Get the device status, in particular, the name of it's device file */
794 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
795 if (ioctl(fd, DM_DEV_STATUS, io)) {
796 SLOGE("Cannot retrieve dm-crypt device status\n");
797 goto errout;
798 }
799 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
800 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
801
Ken Sumralldb5e0262013-02-05 17:39:48 -0800802 extra_params = "";
803 if (! get_dm_crypt_version(fd, name, version)) {
804 /* Support for allow_discards was added in version 1.11.0 */
805 if ((version[0] >= 2) ||
806 ((version[0] == 1) && (version[1] >= 11))) {
807 extra_params = "1 allow_discards";
808 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
809 }
Ken Sumralle919efe2012-09-29 17:07:41 -0700810 }
811
Ken Sumralldb5e0262013-02-05 17:39:48 -0800812 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
813 fd, extra_params);
814 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800815 SLOGE("Cannot load dm-crypt mapping table.\n");
816 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800817 } else if (load_count > 1) {
818 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800819 }
820
821 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -0800822 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800823
824 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
825 SLOGE("Cannot resume the dm-crypt device\n");
826 goto errout;
827 }
828
829 /* We made it here with no errors. Woot! */
830 retval = 0;
831
832errout:
833 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
834
835 return retval;
836}
837
Ken Sumrall29d8da82011-05-18 17:20:07 -0700838static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800839{
840 int fd;
841 char buffer[DM_CRYPT_BUF_SIZE];
842 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800843 int retval = -1;
844
845 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
846 SLOGE("Cannot open device-mapper\n");
847 goto errout;
848 }
849
850 io = (struct dm_ioctl *) buffer;
851
852 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
853 if (ioctl(fd, DM_DEV_REMOVE, io)) {
854 SLOGE("Cannot remove dm-crypt device\n");
855 goto errout;
856 }
857
858 /* We made it here with no errors. Woot! */
859 retval = 0;
860
861errout:
862 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
863
864 return retval;
865
866}
867
Kenny Rootc4c70f12013-06-14 12:11:38 -0700868static void pbkdf2(char *passwd, unsigned char *salt, unsigned char *ikey, void *params) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800869 /* Turn the password into a key and IV that can decrypt the master key */
Ken Sumralle8744072011-01-18 22:01:55 -0800870 PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800871 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800872}
873
Kenny Rootc4c70f12013-06-14 12:11:38 -0700874static void scrypt(char *passwd, unsigned char *salt, unsigned char *ikey, void *params) {
875 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
876
877 int N = 1 << ftr->N_factor;
878 int r = 1 << ftr->r_factor;
879 int p = 1 << ftr->p_factor;
880
881 /* Turn the password into a key and IV that can decrypt the master key */
882 crypto_scrypt((unsigned char *) passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
883 KEY_LEN_BYTES + IV_LEN_BYTES);
884}
885
Ken Sumralle8744072011-01-18 22:01:55 -0800886static int encrypt_master_key(char *passwd, unsigned char *salt,
887 unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700888 unsigned char *encrypted_master_key,
889 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800890{
891 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
892 EVP_CIPHER_CTX e_ctx;
893 int encrypted_len, final_len;
894
895 /* Turn the password into a key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700896 get_device_scrypt_params(crypt_ftr);
897 scrypt(passwd, salt, ikey, crypt_ftr);
898
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800899 /* Initialize the decryption engine */
900 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
901 SLOGE("EVP_EncryptInit failed\n");
902 return -1;
903 }
904 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800905
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800906 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800907 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
908 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800909 SLOGE("EVP_EncryptUpdate failed\n");
910 return -1;
911 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800912 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800913 SLOGE("EVP_EncryptFinal failed\n");
914 return -1;
915 }
916
917 if (encrypted_len + final_len != KEY_LEN_BYTES) {
918 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
919 return -1;
920 } else {
921 return 0;
922 }
923}
924
Ken Sumralle8744072011-01-18 22:01:55 -0800925static int decrypt_master_key(char *passwd, unsigned char *salt,
926 unsigned char *encrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700927 unsigned char *decrypted_master_key,
928 kdf_func kdf, void *kdf_params)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800929{
930 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 -0800931 EVP_CIPHER_CTX d_ctx;
932 int decrypted_len, final_len;
933
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800934 /* Turn the password into a key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700935 kdf(passwd, salt, ikey, kdf_params);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800936
937 /* Initialize the decryption engine */
938 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
939 return -1;
940 }
941 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
942 /* Decrypt the master key */
943 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
944 encrypted_master_key, KEY_LEN_BYTES)) {
945 return -1;
946 }
947 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
948 return -1;
949 }
950
951 if (decrypted_len + final_len != KEY_LEN_BYTES) {
952 return -1;
953 } else {
954 return 0;
955 }
956}
957
Kenny Rootc4c70f12013-06-14 12:11:38 -0700958static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800959{
Kenny Rootc4c70f12013-06-14 12:11:38 -0700960 if (ftr->kdf_type == KDF_SCRYPT) {
961 *kdf = scrypt;
962 *kdf_params = ftr;
963 } else {
964 *kdf = pbkdf2;
965 *kdf_params = NULL;
966 }
967}
968
969static int decrypt_master_key_and_upgrade(char *passwd, unsigned char *decrypted_master_key,
970 struct crypt_mnt_ftr *crypt_ftr)
971{
972 kdf_func kdf;
973 void *kdf_params;
974 int ret;
975
976 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
977 ret = decrypt_master_key(passwd, crypt_ftr->salt, crypt_ftr->master_key, decrypted_master_key, kdf,
978 kdf_params);
979 if (ret != 0) {
980 SLOGW("failure decrypting master key");
981 return ret;
982 }
983
984 /*
985 * Upgrade if we're not using the latest KDF.
986 */
987 if (crypt_ftr->kdf_type != KDF_SCRYPT) {
988 crypt_ftr->kdf_type = KDF_SCRYPT;
989 encrypt_master_key(passwd, crypt_ftr->salt, decrypted_master_key, crypt_ftr->master_key,
990 crypt_ftr);
991 put_crypt_ftr_and_key(crypt_ftr);
992 }
993
994 return ret;
995}
996
997static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
998 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800999 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001000 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001001 EVP_CIPHER_CTX e_ctx;
1002 int encrypted_len, final_len;
1003
1004 /* Get some random bits for a key */
1005 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001006 read(fd, key_buf, sizeof(key_buf));
1007 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001008 close(fd);
1009
1010 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001011 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001012}
1013
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001014static int wait_and_unmount(char *mountpoint)
1015{
1016 int i, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001017#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001018
1019 /* Now umount the tmpfs filesystem */
1020 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
1021 if (umount(mountpoint)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001022 if (errno == EINVAL) {
1023 /* EINVAL is returned if the directory is not a mountpoint,
1024 * i.e. there is no filesystem mounted there. So just get out.
1025 */
1026 break;
1027 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001028 sleep(1);
1029 i++;
1030 } else {
1031 break;
1032 }
1033 }
1034
1035 if (i < WAIT_UNMOUNT_COUNT) {
1036 SLOGD("unmounting %s succeeded\n", mountpoint);
1037 rc = 0;
1038 } else {
1039 SLOGE("unmounting %s failed\n", mountpoint);
1040 rc = -1;
1041 }
1042
1043 return rc;
1044}
1045
Ken Sumrallc5872692013-05-14 15:26:31 -07001046#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001047static int prep_data_fs(void)
1048{
1049 int i;
1050
1051 /* Do the prep of the /data filesystem */
1052 property_set("vold.post_fs_data_done", "0");
1053 property_set("vold.decrypt", "trigger_post_fs_data");
1054 SLOGD("Just triggered post_fs_data\n");
1055
Ken Sumrallc5872692013-05-14 15:26:31 -07001056 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001057 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001058 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001059
1060 property_get("vold.post_fs_data_done", p, "0");
1061 if (*p == '1') {
1062 break;
1063 } else {
1064 usleep(250000);
1065 }
1066 }
1067 if (i == DATA_PREP_TIMEOUT) {
1068 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001069 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001070 return -1;
1071 } else {
1072 SLOGD("post_fs_data done\n");
1073 return 0;
1074 }
1075}
1076
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001077int cryptfs_restart(void)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001078{
1079 char fs_type[32];
1080 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001081 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001082 char fs_options[256];
1083 unsigned long mnt_flags;
1084 struct stat statbuf;
1085 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001086 static int restart_successful = 0;
1087
1088 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001089 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001090 SLOGE("Encrypted filesystem not validated, aborting");
1091 return -1;
1092 }
1093
1094 if (restart_successful) {
1095 SLOGE("System already restarted with encrypted disk, aborting");
1096 return -1;
1097 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001098
1099 /* Here is where we shut down the framework. The init scripts
1100 * start all services in one of three classes: core, main or late_start.
1101 * On boot, we start core and main. Now, we stop main, but not core,
1102 * as core includes vold and a few other really important things that
1103 * we need to keep running. Once main has stopped, we should be able
1104 * to umount the tmpfs /data, then mount the encrypted /data.
1105 * We then restart the class main, and also the class late_start.
1106 * At the moment, I've only put a few things in late_start that I know
1107 * are not needed to bring up the framework, and that also cause problems
1108 * with unmounting the tmpfs /data, but I hope to add add more services
1109 * to the late_start class as we optimize this to decrease the delay
1110 * till the user is asked for the password to the filesystem.
1111 */
1112
1113 /* The init files are setup to stop the class main when vold.decrypt is
1114 * set to trigger_reset_main.
1115 */
1116 property_set("vold.decrypt", "trigger_reset_main");
1117 SLOGD("Just asked init to shut down class main\n");
1118
Ken Sumrall92736ef2012-10-17 20:57:14 -07001119 /* Ugh, shutting down the framework is not synchronous, so until it
1120 * can be fixed, this horrible hack will wait a moment for it all to
1121 * shut down before proceeding. Without it, some devices cannot
1122 * restart the graphics services.
1123 */
1124 sleep(2);
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001125
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001126 /* Now that the framework is shutdown, we should be able to umount()
1127 * the tmpfs filesystem, and mount the real one.
1128 */
1129
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001130 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1131 if (strlen(crypto_blkdev) == 0) {
1132 SLOGE("fs_crypto_blkdev not set\n");
1133 return -1;
1134 }
1135
Ken Sumralle5032c42012-04-01 23:58:44 -07001136 if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
1137 /* If that succeeded, then mount the decrypted filesystem */
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001138 fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001139
Ken Sumralle5032c42012-04-01 23:58:44 -07001140 property_set("vold.decrypt", "trigger_load_persist_props");
1141 /* Create necessary paths on /data */
1142 if (prep_data_fs()) {
1143 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001144 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001145
1146 /* startup service classes main and late_start */
1147 property_set("vold.decrypt", "trigger_restart_framework");
1148 SLOGD("Just triggered restart_framework\n");
1149
1150 /* Give it a few moments to get started */
1151 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001152 }
1153
Ken Sumrall0cc16632011-01-18 20:32:26 -08001154 if (rc == 0) {
1155 restart_successful = 1;
1156 }
1157
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001158 return rc;
1159}
1160
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001161static int do_crypto_complete(char *mount_point)
1162{
1163 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001164 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001165 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001166
1167 property_get("ro.crypto.state", encrypted_state, "");
1168 if (strcmp(encrypted_state, "encrypted") ) {
1169 SLOGE("not running with encryption, aborting");
1170 return 1;
1171 }
1172
Ken Sumrall160b4d62013-04-22 12:15:39 -07001173 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001174 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001175
Ken Sumralle1a45852011-12-14 21:24:27 -08001176 /*
1177 * Only report this error if key_loc is a file and it exists.
1178 * If the device was never encrypted, and /data is not mountable for
1179 * some reason, returning 1 should prevent the UI from presenting the
1180 * a "enter password" screen, or worse, a "press button to wipe the
1181 * device" screen.
1182 */
1183 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1184 SLOGE("master key file does not exist, aborting");
1185 return 1;
1186 } else {
1187 SLOGE("Error getting crypt footer and key\n");
1188 return -1;
1189 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001190 }
1191
1192 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1193 SLOGE("Encryption process didn't finish successfully\n");
1194 return -2; /* -2 is the clue to the UI that there is no usable data on the disk,
1195 * and give the user an option to wipe the disk */
1196 }
1197
1198 /* We passed the test! We shall diminish, and return to the west */
1199 return 0;
1200}
1201
Ken Sumrall29d8da82011-05-18 17:20:07 -07001202static int test_mount_encrypted_fs(char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001203{
1204 struct crypt_mnt_ftr crypt_ftr;
1205 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001206 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001207 char crypto_blkdev[MAXPATHLEN];
1208 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001209 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001210 unsigned int orig_failed_decrypt_count;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001211 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001212 int rc;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001213 kdf_func kdf;
1214 void *kdf_params;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001215
Ken Sumrall0cc16632011-01-18 20:32:26 -08001216 property_get("ro.crypto.state", encrypted_state, "");
Jason parks70a4b3f2011-01-28 10:10:47 -06001217 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001218 SLOGE("encrypted fs already validated or not running with encryption, aborting");
1219 return -1;
1220 }
1221
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001222 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001223
Ken Sumrall160b4d62013-04-22 12:15:39 -07001224 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001225 SLOGE("Error getting crypt footer and key\n");
1226 return -1;
1227 }
Ken Sumralld33d4172011-02-01 00:49:13 -08001228
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001229 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr.fs_size);
1230 orig_failed_decrypt_count = crypt_ftr.failed_decrypt_count;
1231
1232 if (! (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001233 decrypt_master_key_and_upgrade(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001234 }
1235
1236 if (create_crypto_blk_dev(&crypt_ftr, decrypted_master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -07001237 real_blkdev, crypto_blkdev, label)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001238 SLOGE("Error creating decrypted block device\n");
1239 return -1;
1240 }
1241
Alex Klyubin707795a2013-05-10 15:17:07 -07001242 /* If init detects an encrypted filesystem, it writes a file for each such
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001243 * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
1244 * files and passes that data to me */
1245 /* Create a tmp mount point to try mounting the decryptd fs
1246 * Since we're here, the mount_point should be a tmpfs filesystem, so make
1247 * a directory in it to test mount the decrypted filesystem.
1248 */
1249 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1250 mkdir(tmp_mount_point, 0755);
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001251 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001252 SLOGE("Error temp mounting decrypted block device\n");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001253 delete_crypto_blk_dev(label);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001254 crypt_ftr.failed_decrypt_count++;
1255 } else {
1256 /* Success, so just umount and we'll mount it properly when we restart
1257 * the framework.
1258 */
1259 umount(tmp_mount_point);
1260 crypt_ftr.failed_decrypt_count = 0;
1261 }
1262
1263 if (orig_failed_decrypt_count != crypt_ftr.failed_decrypt_count) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001264 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001265 }
1266
1267 if (crypt_ftr.failed_decrypt_count) {
1268 /* We failed to mount the device, so return an error */
1269 rc = crypt_ftr.failed_decrypt_count;
1270
1271 } else {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001272 /* Woot! Success! Save the name of the crypto block device
1273 * so we can mount it when restarting the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001274 */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001275 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001276
1277 /* Also save a the master key so we can reencrypted the key
1278 * the key when we want to change the password on it.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001279 */
Jason parks70a4b3f2011-01-28 10:10:47 -06001280 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001281 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001282 master_key_saved = 1;
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001283 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001284 }
1285
1286 return rc;
1287}
1288
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001289/* Called by vold when it wants to undo the crypto mapping of a volume it
1290 * manages. This is usually in response to a factory reset, when we want
1291 * to undo the crypto mapping so the volume is formatted in the clear.
1292 */
1293int cryptfs_revert_volume(const char *label)
1294{
1295 return delete_crypto_blk_dev((char *)label);
1296}
1297
Ken Sumrall29d8da82011-05-18 17:20:07 -07001298/*
1299 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1300 * Setup a dm-crypt mapping, use the saved master key from
1301 * setting up the /data mapping, and return the new device path.
1302 */
1303int cryptfs_setup_volume(const char *label, int major, int minor,
1304 char *crypto_sys_path, unsigned int max_path,
1305 int *new_major, int *new_minor)
1306{
1307 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1308 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001309 struct stat statbuf;
1310 int nr_sec, fd;
1311
1312 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1313
Ken Sumrall160b4d62013-04-22 12:15:39 -07001314 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001315
1316 /* Update the fs_size field to be the size of the volume */
1317 fd = open(real_blkdev, O_RDONLY);
1318 nr_sec = get_blkdev_size(fd);
1319 close(fd);
1320 if (nr_sec == 0) {
1321 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1322 return -1;
1323 }
1324
1325 sd_crypt_ftr.fs_size = nr_sec;
1326 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1327 crypto_blkdev, label);
1328
1329 stat(crypto_blkdev, &statbuf);
1330 *new_major = MAJOR(statbuf.st_rdev);
1331 *new_minor = MINOR(statbuf.st_rdev);
1332
1333 /* Create path to sys entry for this block device */
1334 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1335
1336 return 0;
1337}
1338
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001339int cryptfs_crypto_complete(void)
1340{
1341 return do_crypto_complete("/data");
1342}
1343
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001344int cryptfs_check_passwd(char *passwd)
1345{
1346 int rc = -1;
1347
Ken Sumrall29d8da82011-05-18 17:20:07 -07001348 rc = test_mount_encrypted_fs(passwd, DATA_MNT_POINT, "userdata");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001349
1350 return rc;
1351}
1352
Ken Sumrall3ad90722011-10-04 20:38:29 -07001353int cryptfs_verify_passwd(char *passwd)
1354{
1355 struct crypt_mnt_ftr crypt_ftr;
1356 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001357 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001358 char encrypted_state[PROPERTY_VALUE_MAX];
1359 int rc;
1360
1361 property_get("ro.crypto.state", encrypted_state, "");
1362 if (strcmp(encrypted_state, "encrypted") ) {
1363 SLOGE("device not encrypted, aborting");
1364 return -2;
1365 }
1366
1367 if (!master_key_saved) {
1368 SLOGE("encrypted fs not yet mounted, aborting");
1369 return -1;
1370 }
1371
1372 if (!saved_mount_point) {
1373 SLOGE("encrypted fs failed to save mount point, aborting");
1374 return -1;
1375 }
1376
Ken Sumrall160b4d62013-04-22 12:15:39 -07001377 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001378 SLOGE("Error getting crypt footer and key\n");
1379 return -1;
1380 }
1381
1382 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1383 /* If the device has no password, then just say the password is valid */
1384 rc = 0;
1385 } else {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001386 decrypt_master_key_and_upgrade(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001387 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1388 /* They match, the password is correct */
1389 rc = 0;
1390 } else {
1391 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1392 sleep(1);
1393 rc = 1;
1394 }
1395 }
1396
1397 return rc;
1398}
1399
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001400/* Initialize a crypt_mnt_ftr structure. The keysize is
1401 * defaulted to 16 bytes, and the filesystem size to 0.
1402 * Presumably, at a minimum, the caller will update the
1403 * filesystem size and crypto_type_name after calling this function.
1404 */
1405static void cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
1406{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001407 off64_t off;
1408
1409 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001410 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001411 ftr->major_version = CURRENT_MAJOR_VERSION;
1412 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001413 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001414 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001415
Kenny Rootc4c70f12013-06-14 12:11:38 -07001416 ftr->kdf_type = KDF_SCRYPT;
1417 get_device_scrypt_params(ftr);
1418
Ken Sumrall160b4d62013-04-22 12:15:39 -07001419 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1420 if (get_crypt_ftr_info(NULL, &off) == 0) {
1421 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1422 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1423 ftr->persist_data_size;
1424 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001425}
1426
Ken Sumrall29d8da82011-05-18 17:20:07 -07001427static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001428{
Ken Sumralle550f782013-08-20 13:48:23 -07001429 const char *args[10];
1430 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1431 int num_args;
1432 int status;
1433 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001434 int rc = -1;
1435
Ken Sumrall29d8da82011-05-18 17:20:07 -07001436 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001437 args[0] = "/system/bin/make_ext4fs";
1438 args[1] = "-a";
1439 args[2] = "/data";
1440 args[3] = "-l";
1441 snprintf(size_str, sizeof(size_str), "%lld", size * 512);
1442 args[4] = size_str;
1443 args[5] = crypto_blkdev;
1444 num_args = 6;
1445 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1446 args[0], args[1], args[2], args[3], args[4], args[5]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001447 } else if (type== FAT_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001448 args[0] = "/system/bin/newfs_msdos";
1449 args[1] = "-F";
1450 args[2] = "32";
1451 args[3] = "-O";
1452 args[4] = "android";
1453 args[5] = "-c";
1454 args[6] = "8";
1455 args[7] = "-s";
1456 snprintf(size_str, sizeof(size_str), "%lld", size);
1457 args[8] = size_str;
1458 args[9] = crypto_blkdev;
1459 num_args = 10;
1460 SLOGI("Making empty filesystem with command %s %s %s %s %s %s %s %s %s %s\n",
1461 args[0], args[1], args[2], args[3], args[4], args[5],
1462 args[6], args[7], args[8], args[9]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001463 } else {
1464 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1465 return -1;
1466 }
1467
Ken Sumralle550f782013-08-20 13:48:23 -07001468 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1469
1470 if (tmp != 0) {
1471 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001472 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07001473 if (WIFEXITED(status)) {
1474 if (WEXITSTATUS(status)) {
1475 SLOGE("Error creating filesystem on %s, exit status %d ",
1476 crypto_blkdev, WEXITSTATUS(status));
1477 } else {
1478 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
1479 rc = 0;
1480 }
1481 } else {
1482 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
1483 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001484 }
1485
1486 return rc;
1487}
1488
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001489#define CRYPT_INPLACE_BUFSIZE 4096
1490#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / 512)
Ken Sumrall29d8da82011-05-18 17:20:07 -07001491static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev, off64_t size,
1492 off64_t *size_already_done, off64_t tot_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001493{
1494 int realfd, cryptofd;
1495 char *buf[CRYPT_INPLACE_BUFSIZE];
1496 int rc = -1;
1497 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001498 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001499 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001500
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001501 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
1502 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
1503 return -1;
1504 }
1505
1506 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
1507 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1508 close(realfd);
1509 return -1;
1510 }
1511
1512 /* This is pretty much a simple loop of reading 4K, and writing 4K.
1513 * The size passed in is the number of 512 byte sectors in the filesystem.
1514 * So compute the number of whole 4K blocks we should read/write,
1515 * and the remainder.
1516 */
1517 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
1518 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001519 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
1520 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001521
1522 SLOGE("Encrypting filesystem in place...");
1523
Ken Sumrall29d8da82011-05-18 17:20:07 -07001524 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001525 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001526 /* process the majority of the filesystem in blocks */
1527 for (i=0; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001528 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001529 if (new_pct > cur_pct) {
1530 char buf[8];
1531
1532 cur_pct = new_pct;
1533 snprintf(buf, sizeof(buf), "%lld", cur_pct);
1534 property_set("vold.encrypt_progress", buf);
1535 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001536 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1537 SLOGE("Error reading real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1538 goto errout;
1539 }
1540 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1541 SLOGE("Error writing crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1542 goto errout;
1543 }
1544 }
1545
1546 /* Do any remaining sectors */
1547 for (i=0; i<remainder; i++) {
1548 if (unix_read(realfd, buf, 512) <= 0) {
1549 SLOGE("Error reading rival sectors from real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1550 goto errout;
1551 }
1552 if (unix_write(cryptofd, buf, 512) <= 0) {
1553 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1554 goto errout;
1555 }
1556 }
1557
Ken Sumrall29d8da82011-05-18 17:20:07 -07001558 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001559 rc = 0;
1560
1561errout:
1562 close(realfd);
1563 close(cryptofd);
1564
1565 return rc;
1566}
1567
1568#define CRYPTO_ENABLE_WIPE 1
1569#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001570
1571#define FRAMEWORK_BOOT_WAIT 60
1572
Ken Sumrall29d8da82011-05-18 17:20:07 -07001573static inline int should_encrypt(struct volume_info *volume)
1574{
1575 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
1576 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
1577}
1578
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001579int cryptfs_enable(char *howarg, char *passwd)
1580{
1581 int how = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001582 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN], sd_crypto_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07001583 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001584 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07001585 int rc=-1, fd, i, ret;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001586 struct crypt_mnt_ftr crypt_ftr, sd_crypt_ftr;;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001587 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001588 char tmpfs_options[PROPERTY_VALUE_MAX];
1589 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001590 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07001591 char key_loc[PROPERTY_VALUE_MAX];
1592 char fuse_sdcard[PROPERTY_VALUE_MAX];
1593 char *sd_mnt_point;
1594 char sd_blk_dev[256] = { 0 };
1595 int num_vols;
1596 struct volume_info *vol_list = 0;
1597 off64_t cur_encryption_done=0, tot_encryption_size=0;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001598
1599 property_get("ro.crypto.state", encrypted_state, "");
1600 if (strcmp(encrypted_state, "unencrypted")) {
1601 SLOGE("Device is already running encrypted, aborting");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001602 goto error_unencrypted;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001603 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001604
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001605 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001606
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001607 if (!strcmp(howarg, "wipe")) {
1608 how = CRYPTO_ENABLE_WIPE;
1609 } else if (! strcmp(howarg, "inplace")) {
1610 how = CRYPTO_ENABLE_INPLACE;
1611 } else {
1612 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08001613 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001614 }
1615
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001616 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001617
Ken Sumrall3ed82362011-01-28 23:31:16 -08001618 /* Get the size of the real block device */
1619 fd = open(real_blkdev, O_RDONLY);
1620 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
1621 SLOGE("Cannot get size of block device %s\n", real_blkdev);
1622 goto error_unencrypted;
1623 }
1624 close(fd);
1625
1626 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001627 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001628 unsigned int fs_size_sec, max_fs_size_sec;
1629
1630 fs_size_sec = get_fs_size(real_blkdev);
1631 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1632
1633 if (fs_size_sec > max_fs_size_sec) {
1634 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
1635 goto error_unencrypted;
1636 }
1637 }
1638
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001639 /* Get a wakelock as this may take a while, and we don't want the
1640 * device to sleep on us. We'll grab a partial wakelock, and if the UI
1641 * wants to keep the screen on, it can grab a full wakelock.
1642 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001643 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001644 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
1645
Jeff Sharkey7382f812012-08-23 14:08:59 -07001646 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07001647 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07001648 if (!sd_mnt_point) {
1649 sd_mnt_point = getenv("EXTERNAL_STORAGE");
1650 }
1651 if (!sd_mnt_point) {
1652 sd_mnt_point = "/mnt/sdcard";
1653 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07001654
1655 num_vols=vold_getNumDirectVolumes();
1656 vol_list = malloc(sizeof(struct volume_info) * num_vols);
1657 vold_getDirectVolumeList(vol_list);
1658
1659 for (i=0; i<num_vols; i++) {
1660 if (should_encrypt(&vol_list[i])) {
1661 fd = open(vol_list[i].blk_dev, O_RDONLY);
1662 if ( (vol_list[i].size = get_blkdev_size(fd)) == 0) {
1663 SLOGE("Cannot get size of block device %s\n", vol_list[i].blk_dev);
1664 goto error_unencrypted;
1665 }
1666 close(fd);
1667
Ken Sumrall3b170052011-07-11 15:38:57 -07001668 ret=vold_disableVol(vol_list[i].label);
Ken Sumrall319b1042011-06-14 14:01:55 -07001669 if ((ret < 0) && (ret != UNMOUNT_NOT_MOUNTED_ERR)) {
1670 /* -2 is returned when the device exists but is not currently mounted.
1671 * ignore the error and continue. */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001672 SLOGE("Failed to unmount volume %s\n", vol_list[i].label);
1673 goto error_unencrypted;
1674 }
1675 }
1676 }
1677
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001678 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001679 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001680 */
1681 property_set("vold.decrypt", "trigger_shutdown_framework");
1682 SLOGD("Just asked init to shut down class main\n");
1683
Ken Sumrall425524d2012-06-14 20:55:28 -07001684 if (vold_unmountAllAsecs()) {
1685 /* Just report the error. If any are left mounted,
1686 * umounting /data below will fail and handle the error.
1687 */
1688 SLOGE("Error unmounting internal asecs");
1689 }
1690
Ken Sumrall29d8da82011-05-18 17:20:07 -07001691 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
1692 if (!strcmp(fuse_sdcard, "true")) {
1693 /* This is a device using the fuse layer to emulate the sdcard semantics
1694 * on top of the userdata partition. vold does not manage it, it is managed
1695 * by the sdcard service. The sdcard service was killed by the property trigger
1696 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
1697 * unlike the case for vold managed devices above.
1698 */
1699 if (wait_and_unmount(sd_mnt_point)) {
1700 goto error_shutting_down;
1701 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001702 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001703
1704 /* Now unmount the /data partition. */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001705 if (wait_and_unmount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001706 goto error_shutting_down;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001707 }
1708
1709 /* Do extra work for a better UX when doing the long inplace encryption */
1710 if (how == CRYPTO_ENABLE_INPLACE) {
1711 /* Now that /data is unmounted, we need to mount a tmpfs
1712 * /data, set a property saying we're doing inplace encryption,
1713 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001714 */
Ken Sumralle5032c42012-04-01 23:58:44 -07001715 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001716 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001717 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001718 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08001719 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001720
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001721 /* restart the framework. */
1722 /* Create necessary paths on /data */
1723 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001724 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001725 }
1726
Ken Sumrall92736ef2012-10-17 20:57:14 -07001727 /* Ugh, shutting down the framework is not synchronous, so until it
1728 * can be fixed, this horrible hack will wait a moment for it all to
1729 * shut down before proceeding. Without it, some devices cannot
1730 * restart the graphics services.
1731 */
1732 sleep(2);
1733
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001734 /* startup service classes main and late_start */
1735 property_set("vold.decrypt", "trigger_restart_min_framework");
1736 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001737
Ken Sumrall7df84122011-01-18 14:04:08 -08001738 /* OK, the framework is restarted and will soon be showing a
1739 * progress bar. Time to setup an encrypted mapping, and
1740 * either write a new filesystem, or encrypt in place updating
1741 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001742 */
1743 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001744
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001745 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001746 /* Initialize a crypt_mnt_ftr for the partition */
1747 cryptfs_init_crypt_mnt_ftr(&crypt_ftr);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001748
Ken Sumrall29d8da82011-05-18 17:20:07 -07001749 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
1750 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1751 } else {
1752 crypt_ftr.fs_size = nr_sec;
1753 }
Ken Sumralld33d4172011-02-01 00:49:13 -08001754 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001755 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
1756
1757 /* Make an encrypted master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001758 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001759 SLOGE("Cannot create encrypted master key\n");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001760 goto error_unencrypted;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001761 }
1762
1763 /* Write the key to the end of the partition */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001764 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001765
Ken Sumrall160b4d62013-04-22 12:15:39 -07001766 /* If any persistent data has been remembered, save it.
1767 * If none, create a valid empty table and save that.
1768 */
1769 if (!persist_data) {
1770 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
1771 if (pdata) {
1772 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
1773 persist_data = pdata;
1774 }
1775 }
1776 if (persist_data) {
1777 save_persistent_data();
1778 }
1779
Kenny Rootc4c70f12013-06-14 12:11:38 -07001780 decrypt_master_key_and_upgrade(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001781 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
1782 "userdata");
1783
Ken Sumrall128626f2011-06-28 18:45:14 -07001784 /* The size of the userdata partition, and add in the vold volumes below */
1785 tot_encryption_size = crypt_ftr.fs_size;
1786
Ken Sumrall29d8da82011-05-18 17:20:07 -07001787 /* setup crypto mapping for all encryptable volumes handled by vold */
1788 for (i=0; i<num_vols; i++) {
1789 if (should_encrypt(&vol_list[i])) {
1790 vol_list[i].crypt_ftr = crypt_ftr; /* gotta love struct assign */
1791 vol_list[i].crypt_ftr.fs_size = vol_list[i].size;
1792 create_crypto_blk_dev(&vol_list[i].crypt_ftr, decrypted_master_key,
1793 vol_list[i].blk_dev, vol_list[i].crypto_blkdev,
1794 vol_list[i].label);
Ken Sumrall128626f2011-06-28 18:45:14 -07001795 tot_encryption_size += vol_list[i].size;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001796 }
1797 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001798
1799 if (how == CRYPTO_ENABLE_WIPE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001800 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr.fs_size, EXT4_FS);
1801 /* Encrypt all encryptable volumes handled by vold */
1802 if (!rc) {
1803 for (i=0; i<num_vols; i++) {
1804 if (should_encrypt(&vol_list[i])) {
1805 rc = cryptfs_enable_wipe(vol_list[i].crypto_blkdev,
1806 vol_list[i].crypt_ftr.fs_size, FAT_FS);
1807 }
1808 }
1809 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001810 } else if (how == CRYPTO_ENABLE_INPLACE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001811 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr.fs_size,
1812 &cur_encryption_done, tot_encryption_size);
1813 /* Encrypt all encryptable volumes handled by vold */
1814 if (!rc) {
1815 for (i=0; i<num_vols; i++) {
1816 if (should_encrypt(&vol_list[i])) {
1817 rc = cryptfs_enable_inplace(vol_list[i].crypto_blkdev,
1818 vol_list[i].blk_dev,
1819 vol_list[i].crypt_ftr.fs_size,
1820 &cur_encryption_done, tot_encryption_size);
1821 }
1822 }
1823 }
1824 if (!rc) {
1825 /* The inplace routine never actually sets the progress to 100%
1826 * due to the round down nature of integer division, so set it here */
1827 property_set("vold.encrypt_progress", "100");
1828 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001829 } else {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001830 /* Shouldn't happen */
1831 SLOGE("cryptfs_enable: internal error, unknown option\n");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001832 goto error_unencrypted;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001833 }
1834
1835 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001836 delete_crypto_blk_dev("userdata");
1837 for (i=0; i<num_vols; i++) {
1838 if (should_encrypt(&vol_list[i])) {
1839 delete_crypto_blk_dev(vol_list[i].label);
1840 }
1841 }
1842
1843 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001844
1845 if (! rc) {
1846 /* Success */
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001847
Ken Sumralld33d4172011-02-01 00:49:13 -08001848 /* Clear the encryption in progres flag in the footer */
1849 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001850 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08001851
Ken Sumrall29d8da82011-05-18 17:20:07 -07001852 sleep(2); /* Give the UI a chance to show 100% progress */
Ken Sumralladfba362013-06-04 16:37:52 -07001853 cryptfs_reboot(0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001854 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001855 char value[PROPERTY_VALUE_MAX];
1856
Ken Sumrall319369a2012-06-27 16:30:18 -07001857 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001858 if (!strcmp(value, "1")) {
1859 /* wipe data if encryption failed */
1860 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
1861 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07001862 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001863 if (fd >= 0) {
1864 write(fd, "--wipe_data", strlen("--wipe_data") + 1);
1865 close(fd);
1866 } else {
1867 SLOGE("could not open /cache/recovery/command\n");
1868 }
Ken Sumralladfba362013-06-04 16:37:52 -07001869 cryptfs_reboot(1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001870 } else {
1871 /* set property to trigger dialog */
1872 property_set("vold.encrypt_progress", "error_partially_encrypted");
1873 release_wake_lock(lockid);
1874 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001875 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001876 }
1877
Ken Sumrall3ed82362011-01-28 23:31:16 -08001878 /* hrm, the encrypt step claims success, but the reboot failed.
1879 * This should not happen.
1880 * Set the property and return. Hope the framework can deal with it.
1881 */
1882 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001883 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001884 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08001885
1886error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07001887 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001888 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001889 if (lockid[0]) {
1890 release_wake_lock(lockid);
1891 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001892 return -1;
1893
1894error_shutting_down:
1895 /* we failed, and have not encrypted anthing, so the users's data is still intact,
1896 * but the framework is stopped and not restarted to show the error, so it's up to
1897 * vold to restart the system.
1898 */
1899 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Ken Sumralladfba362013-06-04 16:37:52 -07001900 cryptfs_reboot(0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001901
1902 /* shouldn't get here */
1903 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001904 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001905 if (lockid[0]) {
1906 release_wake_lock(lockid);
1907 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001908 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001909}
1910
Jason parks70a4b3f2011-01-28 10:10:47 -06001911int cryptfs_changepw(char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001912{
1913 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001914 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001915
1916 /* This is only allowed after we've successfully decrypted the master key */
Jason parks70a4b3f2011-01-28 10:10:47 -06001917 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001918 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001919 return -1;
1920 }
1921
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001922 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001923 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall57b63e62011-01-17 18:29:19 -08001924 SLOGE("Error getting crypt footer and key");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001925 return -1;
1926 }
1927
Kenny Rootc4c70f12013-06-14 12:11:38 -07001928 encrypt_master_key(newpw, crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001929
Jason parks70a4b3f2011-01-28 10:10:47 -06001930 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001931 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001932
1933 return 0;
1934}
Ken Sumrall160b4d62013-04-22 12:15:39 -07001935
1936static int persist_get_key(char *fieldname, char *value)
1937{
1938 unsigned int i;
1939
1940 if (persist_data == NULL) {
1941 return -1;
1942 }
1943 for (i = 0; i < persist_data->persist_valid_entries; i++) {
1944 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
1945 /* We found it! */
1946 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
1947 return 0;
1948 }
1949 }
1950
1951 return -1;
1952}
1953
1954static int persist_set_key(char *fieldname, char *value, int encrypted)
1955{
1956 unsigned int i;
1957 unsigned int num;
1958 struct crypt_mnt_ftr crypt_ftr;
1959 unsigned int max_persistent_entries;
1960 unsigned int dsize;
1961
1962 if (persist_data == NULL) {
1963 return -1;
1964 }
1965
1966 /* If encrypted, use the values from the crypt_ftr, otherwise
1967 * use the values for the current spec.
1968 */
1969 if (encrypted) {
1970 if(get_crypt_ftr_and_key(&crypt_ftr)) {
1971 return -1;
1972 }
1973 dsize = crypt_ftr.persist_data_size;
1974 } else {
1975 dsize = CRYPT_PERSIST_DATA_SIZE;
1976 }
1977 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
1978 sizeof(struct crypt_persist_entry);
1979
1980 num = persist_data->persist_valid_entries;
1981
1982 for (i = 0; i < num; i++) {
1983 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
1984 /* We found an existing entry, update it! */
1985 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
1986 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
1987 return 0;
1988 }
1989 }
1990
1991 /* We didn't find it, add it to the end, if there is room */
1992 if (persist_data->persist_valid_entries < max_persistent_entries) {
1993 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
1994 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
1995 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
1996 persist_data->persist_valid_entries++;
1997 return 0;
1998 }
1999
2000 return -1;
2001}
2002
2003/* Return the value of the specified field. */
2004int cryptfs_getfield(char *fieldname, char *value, int len)
2005{
2006 char temp_value[PROPERTY_VALUE_MAX];
2007 char real_blkdev[MAXPATHLEN];
2008 /* 0 is success, 1 is not encrypted,
2009 * -1 is value not set, -2 is any other error
2010 */
2011 int rc = -2;
2012
2013 if (persist_data == NULL) {
2014 load_persistent_data();
2015 if (persist_data == NULL) {
2016 SLOGE("Getfield error, cannot load persistent data");
2017 goto out;
2018 }
2019 }
2020
2021 if (!persist_get_key(fieldname, temp_value)) {
2022 /* We found it, copy it to the caller's buffer and return */
2023 strlcpy(value, temp_value, len);
2024 rc = 0;
2025 } else {
2026 /* Sadness, it's not there. Return the error */
2027 rc = -1;
2028 }
2029
2030out:
2031 return rc;
2032}
2033
2034/* Set the value of the specified field. */
2035int cryptfs_setfield(char *fieldname, char *value)
2036{
2037 struct crypt_persist_data stored_pdata;
2038 struct crypt_persist_data *pdata_p;
2039 struct crypt_mnt_ftr crypt_ftr;
2040 char encrypted_state[PROPERTY_VALUE_MAX];
2041 /* 0 is success, -1 is an error */
2042 int rc = -1;
2043 int encrypted = 0;
2044
2045 if (persist_data == NULL) {
2046 load_persistent_data();
2047 if (persist_data == NULL) {
2048 SLOGE("Setfield error, cannot load persistent data");
2049 goto out;
2050 }
2051 }
2052
2053 property_get("ro.crypto.state", encrypted_state, "");
2054 if (!strcmp(encrypted_state, "encrypted") ) {
2055 encrypted = 1;
2056 }
2057
2058 if (persist_set_key(fieldname, value, encrypted)) {
2059 goto out;
2060 }
2061
2062 /* If we are running encrypted, save the persistent data now */
2063 if (encrypted) {
2064 if (save_persistent_data()) {
2065 SLOGE("Setfield error, cannot save persistent data");
2066 goto out;
2067 }
2068 }
2069
2070 rc = 0;
2071
2072out:
2073 return rc;
2074}