blob: 76416121dc46b3f01d54110ea4c9e287a5124a18 [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
54
Jason parks70a4b3f2011-01-28 10:10:47 -060055#define HASH_COUNT 2000
56#define KEY_LEN_BYTES 16
57#define IV_LEN_BYTES 16
58
Ken Sumrall29d8da82011-05-18 17:20:07 -070059#define KEY_IN_FOOTER "footer"
60
61#define EXT4_FS 1
62#define FAT_FS 2
63
Ken Sumralle919efe2012-09-29 17:07:41 -070064#define TABLE_LOAD_RETRIES 10
65
Ken Sumrall8f869aa2010-12-03 03:47:09 -080066char *me = "cryptfs";
67
Jason parks70a4b3f2011-01-28 10:10:47 -060068static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070069static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060070static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -070071static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -080072
73extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -080074
Ken Sumralladfba362013-06-04 16:37:52 -070075static void cryptfs_reboot(int recovery)
76{
77 if (recovery) {
78 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
79 } else {
80 property_set(ANDROID_RB_PROPERTY, "reboot");
81 }
82 sleep(20);
83
84 /* Shouldn't get here, reboot should happen before sleep times out */
85 return;
86}
87
Ken Sumrall8f869aa2010-12-03 03:47:09 -080088static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
89{
90 memset(io, 0, dataSize);
91 io->data_size = dataSize;
92 io->data_start = sizeof(struct dm_ioctl);
93 io->version[0] = 4;
94 io->version[1] = 0;
95 io->version[2] = 0;
96 io->flags = flags;
97 if (name) {
98 strncpy(io->name, name, sizeof(io->name));
99 }
100}
101
Kenny Rootc4c70f12013-06-14 12:11:38 -0700102/**
103 * Gets the default device scrypt parameters for key derivation time tuning.
104 * The parameters should lead to about one second derivation time for the
105 * given device.
106 */
107static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
108 const int default_params[] = SCRYPT_DEFAULTS;
109 int params[] = SCRYPT_DEFAULTS;
110 char paramstr[PROPERTY_VALUE_MAX];
111 char *token;
112 char *saveptr;
113 int i;
114
115 property_get(SCRYPT_PROP, paramstr, "");
116 if (paramstr[0] != '\0') {
117 /*
118 * The token we're looking for should be three integers separated by
119 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
120 */
Kenny Root2947e342013-08-14 15:54:49 -0700121 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
122 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700123 i++, token = strtok_r(NULL, ":", &saveptr)) {
124 char *endptr;
125 params[i] = strtol(token, &endptr, 10);
126
127 /*
128 * Check that there was a valid number and it's 8-bit. If not,
129 * break out and the end check will take the default values.
130 */
131 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
132 break;
133 }
134 }
135
136 /*
137 * If there were not enough tokens or a token was malformed (not an
138 * integer), it will end up here and the default parameters can be
139 * taken.
140 */
141 if ((i != 3) || (token != NULL)) {
142 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
143 memcpy(params, default_params, sizeof(params));
144 }
145 }
146
147 ftr->N_factor = params[0];
148 ftr->r_factor = params[1];
149 ftr->p_factor = params[2];
150}
151
Ken Sumrall3ed82362011-01-28 23:31:16 -0800152static unsigned int get_fs_size(char *dev)
153{
154 int fd, block_size;
155 struct ext4_super_block sb;
156 off64_t len;
157
158 if ((fd = open(dev, O_RDONLY)) < 0) {
159 SLOGE("Cannot open device to get filesystem size ");
160 return 0;
161 }
162
163 if (lseek64(fd, 1024, SEEK_SET) < 0) {
164 SLOGE("Cannot seek to superblock");
165 return 0;
166 }
167
168 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
169 SLOGE("Cannot read superblock");
170 return 0;
171 }
172
173 close(fd);
174
175 block_size = 1024 << sb.s_log_block_size;
176 /* compute length in bytes */
177 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
178
179 /* return length in sectors */
180 return (unsigned int) (len / 512);
181}
182
Ken Sumrall160b4d62013-04-22 12:15:39 -0700183static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
184{
185 static int cached_data = 0;
186 static off64_t cached_off = 0;
187 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
188 int fd;
189 char key_loc[PROPERTY_VALUE_MAX];
190 char real_blkdev[PROPERTY_VALUE_MAX];
191 unsigned int nr_sec;
192 int rc = -1;
193
194 if (!cached_data) {
195 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
196
197 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
198 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
199 SLOGE("Cannot open real block device %s\n", real_blkdev);
200 return -1;
201 }
202
203 if ((nr_sec = get_blkdev_size(fd))) {
204 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
205 * encryption info footer and key, and plenty of bytes to spare for future
206 * growth.
207 */
208 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
209 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
210 cached_data = 1;
211 } else {
212 SLOGE("Cannot get size of block device %s\n", real_blkdev);
213 }
214 close(fd);
215 } else {
216 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
217 cached_off = 0;
218 cached_data = 1;
219 }
220 }
221
222 if (cached_data) {
223 if (metadata_fname) {
224 *metadata_fname = cached_metadata_fname;
225 }
226 if (off) {
227 *off = cached_off;
228 }
229 rc = 0;
230 }
231
232 return rc;
233}
234
Ken Sumralle8744072011-01-18 22:01:55 -0800235/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800236 * update the failed mount count but not change the key.
237 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700238static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800239{
240 int fd;
241 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700242 /* starting_off is set to the SEEK_SET offset
243 * where the crypto structure starts
244 */
245 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800246 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700247 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700248 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800249
Ken Sumrall160b4d62013-04-22 12:15:39 -0700250 if (get_crypt_ftr_info(&fname, &starting_off)) {
251 SLOGE("Unable to get crypt_ftr_info\n");
252 return -1;
253 }
254 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700255 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700256 return -1;
257 }
Ken Sumralle550f782013-08-20 13:48:23 -0700258 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
259 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700260 return -1;
261 }
262
263 /* Seek to the start of the crypt footer */
264 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
265 SLOGE("Cannot seek to real block device footer\n");
266 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800267 }
268
269 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
270 SLOGE("Cannot write real block device footer\n");
271 goto errout;
272 }
273
Ken Sumrall3be890f2011-09-14 16:53:46 -0700274 fstat(fd, &statbuf);
275 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700276 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700277 if (ftruncate(fd, 0x4000)) {
Ken Sumrall3be890f2011-09-14 16:53:46 -0700278 SLOGE("Cannot set footer file size\n", fname);
Ken Sumralle8744072011-01-18 22:01:55 -0800279 goto errout;
280 }
281 }
282
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800283 /* Success! */
284 rc = 0;
285
286errout:
287 close(fd);
288 return rc;
289
290}
291
Ken Sumrall160b4d62013-04-22 12:15:39 -0700292static inline int unix_read(int fd, void* buff, int len)
293{
294 return TEMP_FAILURE_RETRY(read(fd, buff, len));
295}
296
297static inline int unix_write(int fd, const void* buff, int len)
298{
299 return TEMP_FAILURE_RETRY(write(fd, buff, len));
300}
301
302static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
303{
304 memset(pdata, 0, len);
305 pdata->persist_magic = PERSIST_DATA_MAGIC;
306 pdata->persist_valid_entries = 0;
307}
308
309/* A routine to update the passed in crypt_ftr to the lastest version.
310 * fd is open read/write on the device that holds the crypto footer and persistent
311 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
312 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
313 */
314static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
315{
Kenny Root7434b312013-06-14 11:29:53 -0700316 int orig_major = crypt_ftr->major_version;
317 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700318
Kenny Root7434b312013-06-14 11:29:53 -0700319 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
320 struct crypt_persist_data *pdata;
321 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700322
Kenny Rootc4c70f12013-06-14 12:11:38 -0700323 SLOGW("upgrading crypto footer to 1.1");
324
Kenny Root7434b312013-06-14 11:29:53 -0700325 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
326 if (pdata == NULL) {
327 SLOGE("Cannot allocate persisent data\n");
328 return;
329 }
330 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
331
332 /* Need to initialize the persistent data area */
333 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
334 SLOGE("Cannot seek to persisent data offset\n");
335 return;
336 }
337 /* Write all zeros to the first copy, making it invalid */
338 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
339
340 /* Write a valid but empty structure to the second copy */
341 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
342 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
343
344 /* Update the footer */
345 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
346 crypt_ftr->persist_data_offset[0] = pdata_offset;
347 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
348 crypt_ftr->minor_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700349 }
350
Kenny Rootc4c70f12013-06-14 12:11:38 -0700351 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version)) {
352 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800353 /* But keep the old kdf_type.
354 * It will get updated later to KDF_SCRYPT after the password has been verified.
355 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700356 crypt_ftr->kdf_type = KDF_PBKDF2;
357 get_device_scrypt_params(crypt_ftr);
358 crypt_ftr->minor_version = 2;
359 }
360
Kenny Root7434b312013-06-14 11:29:53 -0700361 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
362 if (lseek64(fd, offset, SEEK_SET) == -1) {
363 SLOGE("Cannot seek to crypt footer\n");
364 return;
365 }
366 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700367 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700368}
369
370
371static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800372{
373 int fd;
374 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700375 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800376 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700377 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700378 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800379
Ken Sumrall160b4d62013-04-22 12:15:39 -0700380 if (get_crypt_ftr_info(&fname, &starting_off)) {
381 SLOGE("Unable to get crypt_ftr_info\n");
382 return -1;
383 }
384 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700385 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700386 return -1;
387 }
388 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700389 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700390 return -1;
391 }
392
393 /* Make sure it's 16 Kbytes in length */
394 fstat(fd, &statbuf);
395 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
396 SLOGE("footer file %s is not the expected size!\n", fname);
397 goto errout;
398 }
399
400 /* Seek to the start of the crypt footer */
401 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
402 SLOGE("Cannot seek to real block device footer\n");
403 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800404 }
405
406 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
407 SLOGE("Cannot read real block device footer\n");
408 goto errout;
409 }
410
411 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700412 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800413 goto errout;
414 }
415
Kenny Rootc96a5f82013-06-14 12:08:28 -0700416 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
417 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
418 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800419 goto errout;
420 }
421
Kenny Rootc96a5f82013-06-14 12:08:28 -0700422 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
423 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
424 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800425 }
426
Ken Sumrall160b4d62013-04-22 12:15:39 -0700427 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
428 * copy on disk before returning.
429 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700430 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700431 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800432 }
433
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800434 /* Success! */
435 rc = 0;
436
437errout:
438 close(fd);
439 return rc;
440}
441
Ken Sumrall160b4d62013-04-22 12:15:39 -0700442static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
443{
444 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
445 crypt_ftr->persist_data_offset[1]) {
446 SLOGE("Crypt_ftr persist data regions overlap");
447 return -1;
448 }
449
450 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
451 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
452 return -1;
453 }
454
455 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
456 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
457 CRYPT_FOOTER_OFFSET) {
458 SLOGE("Persistent data extends past crypto footer");
459 return -1;
460 }
461
462 return 0;
463}
464
465static int load_persistent_data(void)
466{
467 struct crypt_mnt_ftr crypt_ftr;
468 struct crypt_persist_data *pdata = NULL;
469 char encrypted_state[PROPERTY_VALUE_MAX];
470 char *fname;
471 int found = 0;
472 int fd;
473 int ret;
474 int i;
475
476 if (persist_data) {
477 /* Nothing to do, we've already loaded or initialized it */
478 return 0;
479 }
480
481
482 /* If not encrypted, just allocate an empty table and initialize it */
483 property_get("ro.crypto.state", encrypted_state, "");
484 if (strcmp(encrypted_state, "encrypted") ) {
485 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
486 if (pdata) {
487 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
488 persist_data = pdata;
489 return 0;
490 }
491 return -1;
492 }
493
494 if(get_crypt_ftr_and_key(&crypt_ftr)) {
495 return -1;
496 }
497
498 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
499 SLOGE("Crypt_ftr version doesn't support persistent data");
500 return -1;
501 }
502
503 if (get_crypt_ftr_info(&fname, NULL)) {
504 return -1;
505 }
506
507 ret = validate_persistent_data_storage(&crypt_ftr);
508 if (ret) {
509 return -1;
510 }
511
512 fd = open(fname, O_RDONLY);
513 if (fd < 0) {
514 SLOGE("Cannot open %s metadata file", fname);
515 return -1;
516 }
517
518 if (persist_data == NULL) {
519 pdata = malloc(crypt_ftr.persist_data_size);
520 if (pdata == NULL) {
521 SLOGE("Cannot allocate memory for persistent data");
522 goto err;
523 }
524 }
525
526 for (i = 0; i < 2; i++) {
527 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
528 SLOGE("Cannot seek to read persistent data on %s", fname);
529 goto err2;
530 }
531 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
532 SLOGE("Error reading persistent data on iteration %d", i);
533 goto err2;
534 }
535 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
536 found = 1;
537 break;
538 }
539 }
540
541 if (!found) {
542 SLOGI("Could not find valid persistent data, creating");
543 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
544 }
545
546 /* Success */
547 persist_data = pdata;
548 close(fd);
549 return 0;
550
551err2:
552 free(pdata);
553
554err:
555 close(fd);
556 return -1;
557}
558
559static int save_persistent_data(void)
560{
561 struct crypt_mnt_ftr crypt_ftr;
562 struct crypt_persist_data *pdata;
563 char *fname;
564 off64_t write_offset;
565 off64_t erase_offset;
566 int found = 0;
567 int fd;
568 int ret;
569
570 if (persist_data == NULL) {
571 SLOGE("No persistent data to save");
572 return -1;
573 }
574
575 if(get_crypt_ftr_and_key(&crypt_ftr)) {
576 return -1;
577 }
578
579 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
580 SLOGE("Crypt_ftr version doesn't support persistent data");
581 return -1;
582 }
583
584 ret = validate_persistent_data_storage(&crypt_ftr);
585 if (ret) {
586 return -1;
587 }
588
589 if (get_crypt_ftr_info(&fname, NULL)) {
590 return -1;
591 }
592
593 fd = open(fname, O_RDWR);
594 if (fd < 0) {
595 SLOGE("Cannot open %s metadata file", fname);
596 return -1;
597 }
598
599 pdata = malloc(crypt_ftr.persist_data_size);
600 if (pdata == NULL) {
601 SLOGE("Cannot allocate persistant data");
602 goto err;
603 }
604
605 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
606 SLOGE("Cannot seek to read persistent data on %s", fname);
607 goto err2;
608 }
609
610 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
611 SLOGE("Error reading persistent data before save");
612 goto err2;
613 }
614
615 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
616 /* The first copy is the curent valid copy, so write to
617 * the second copy and erase this one */
618 write_offset = crypt_ftr.persist_data_offset[1];
619 erase_offset = crypt_ftr.persist_data_offset[0];
620 } else {
621 /* The second copy must be the valid copy, so write to
622 * the first copy, and erase the second */
623 write_offset = crypt_ftr.persist_data_offset[0];
624 erase_offset = crypt_ftr.persist_data_offset[1];
625 }
626
627 /* Write the new copy first, if successful, then erase the old copy */
628 if (lseek(fd, write_offset, SEEK_SET) < 0) {
629 SLOGE("Cannot seek to write persistent data");
630 goto err2;
631 }
632 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
633 (int) crypt_ftr.persist_data_size) {
634 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
635 SLOGE("Cannot seek to erase previous persistent data");
636 goto err2;
637 }
638 fsync(fd);
639 memset(pdata, 0, crypt_ftr.persist_data_size);
640 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
641 (int) crypt_ftr.persist_data_size) {
642 SLOGE("Cannot write to erase previous persistent data");
643 goto err2;
644 }
645 fsync(fd);
646 } else {
647 SLOGE("Cannot write to save persistent data");
648 goto err2;
649 }
650
651 /* Success */
652 free(pdata);
653 close(fd);
654 return 0;
655
656err2:
657 free(pdata);
658err:
659 close(fd);
660 return -1;
661}
662
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800663/* Convert a binary key of specified length into an ascii hex string equivalent,
664 * without the leading 0x and with null termination
665 */
666void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
667 char *master_key_ascii)
668{
669 unsigned int i, a;
670 unsigned char nibble;
671
672 for (i=0, a=0; i<keysize; i++, a+=2) {
673 /* For each byte, write out two ascii hex digits */
674 nibble = (master_key[i] >> 4) & 0xf;
675 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
676
677 nibble = master_key[i] & 0xf;
678 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
679 }
680
681 /* Add the null termination */
682 master_key_ascii[a] = '\0';
683
684}
685
Ken Sumralldb5e0262013-02-05 17:39:48 -0800686static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
687 char *real_blk_name, const char *name, int fd,
688 char *extra_params)
689{
690 char buffer[DM_CRYPT_BUF_SIZE];
691 struct dm_ioctl *io;
692 struct dm_target_spec *tgt;
693 char *crypt_params;
694 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
695 int i;
696
697 io = (struct dm_ioctl *) buffer;
698
699 /* Load the mapping table for this device */
700 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
701
702 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
703 io->target_count = 1;
704 tgt->status = 0;
705 tgt->sector_start = 0;
706 tgt->length = crypt_ftr->fs_size;
707 strcpy(tgt->target_type, "crypt");
708
709 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
710 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
711 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
712 master_key_ascii, real_blk_name, extra_params);
713 crypt_params += strlen(crypt_params) + 1;
714 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
715 tgt->next = crypt_params - buffer;
716
717 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
718 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
719 break;
720 }
721 usleep(500000);
722 }
723
724 if (i == TABLE_LOAD_RETRIES) {
725 /* We failed to load the table, return an error */
726 return -1;
727 } else {
728 return i + 1;
729 }
730}
731
732
733static int get_dm_crypt_version(int fd, const char *name, int *version)
734{
735 char buffer[DM_CRYPT_BUF_SIZE];
736 struct dm_ioctl *io;
737 struct dm_target_versions *v;
738 int i;
739
740 io = (struct dm_ioctl *) buffer;
741
742 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
743
744 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
745 return -1;
746 }
747
748 /* Iterate over the returned versions, looking for name of "crypt".
749 * When found, get and return the version.
750 */
751 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
752 while (v->next) {
753 if (! strcmp(v->name, "crypt")) {
754 /* We found the crypt driver, return the version, and get out */
755 version[0] = v->version[0];
756 version[1] = v->version[1];
757 version[2] = v->version[2];
758 return 0;
759 }
760 v = (struct dm_target_versions *)(((char *)v) + v->next);
761 }
762
763 return -1;
764}
765
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800766static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -0700767 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800768{
769 char buffer[DM_CRYPT_BUF_SIZE];
770 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
771 char *crypt_params;
772 struct dm_ioctl *io;
773 struct dm_target_spec *tgt;
774 unsigned int minor;
775 int fd;
Ken Sumralle919efe2012-09-29 17:07:41 -0700776 int i;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800777 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800778 int version[3];
779 char *extra_params;
780 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800781
782 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
783 SLOGE("Cannot open device-mapper\n");
784 goto errout;
785 }
786
787 io = (struct dm_ioctl *) buffer;
788
789 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
790 if (ioctl(fd, DM_DEV_CREATE, io)) {
791 SLOGE("Cannot create dm-crypt device\n");
792 goto errout;
793 }
794
795 /* Get the device status, in particular, the name of it's device file */
796 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
797 if (ioctl(fd, DM_DEV_STATUS, io)) {
798 SLOGE("Cannot retrieve dm-crypt device status\n");
799 goto errout;
800 }
801 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
802 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
803
Ken Sumralldb5e0262013-02-05 17:39:48 -0800804 extra_params = "";
805 if (! get_dm_crypt_version(fd, name, version)) {
806 /* Support for allow_discards was added in version 1.11.0 */
807 if ((version[0] >= 2) ||
808 ((version[0] == 1) && (version[1] >= 11))) {
809 extra_params = "1 allow_discards";
810 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
811 }
Ken Sumralle919efe2012-09-29 17:07:41 -0700812 }
813
Ken Sumralldb5e0262013-02-05 17:39:48 -0800814 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
815 fd, extra_params);
816 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800817 SLOGE("Cannot load dm-crypt mapping table.\n");
818 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800819 } else if (load_count > 1) {
820 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800821 }
822
823 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -0800824 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800825
826 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
827 SLOGE("Cannot resume the dm-crypt device\n");
828 goto errout;
829 }
830
831 /* We made it here with no errors. Woot! */
832 retval = 0;
833
834errout:
835 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
836
837 return retval;
838}
839
Ken Sumrall29d8da82011-05-18 17:20:07 -0700840static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800841{
842 int fd;
843 char buffer[DM_CRYPT_BUF_SIZE];
844 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800845 int retval = -1;
846
847 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
848 SLOGE("Cannot open device-mapper\n");
849 goto errout;
850 }
851
852 io = (struct dm_ioctl *) buffer;
853
854 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
855 if (ioctl(fd, DM_DEV_REMOVE, io)) {
856 SLOGE("Cannot remove dm-crypt device\n");
857 goto errout;
858 }
859
860 /* We made it here with no errors. Woot! */
861 retval = 0;
862
863errout:
864 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
865
866 return retval;
867
868}
869
Kenny Rootc4c70f12013-06-14 12:11:38 -0700870static void pbkdf2(char *passwd, unsigned char *salt, unsigned char *ikey, void *params) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800871 /* Turn the password into a key and IV that can decrypt the master key */
Ken Sumralle8744072011-01-18 22:01:55 -0800872 PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800873 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800874}
875
Kenny Rootc4c70f12013-06-14 12:11:38 -0700876static void scrypt(char *passwd, unsigned char *salt, unsigned char *ikey, void *params) {
877 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
878
879 int N = 1 << ftr->N_factor;
880 int r = 1 << ftr->r_factor;
881 int p = 1 << ftr->p_factor;
882
883 /* Turn the password into a key and IV that can decrypt the master key */
884 crypto_scrypt((unsigned char *) passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
885 KEY_LEN_BYTES + IV_LEN_BYTES);
886}
887
Ken Sumralle8744072011-01-18 22:01:55 -0800888static int encrypt_master_key(char *passwd, unsigned char *salt,
889 unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700890 unsigned char *encrypted_master_key,
891 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800892{
893 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
894 EVP_CIPHER_CTX e_ctx;
895 int encrypted_len, final_len;
896
897 /* Turn the password into a key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700898 get_device_scrypt_params(crypt_ftr);
899 scrypt(passwd, salt, ikey, crypt_ftr);
900
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800901 /* Initialize the decryption engine */
902 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
903 SLOGE("EVP_EncryptInit failed\n");
904 return -1;
905 }
906 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800907
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800908 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800909 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
910 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800911 SLOGE("EVP_EncryptUpdate failed\n");
912 return -1;
913 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800914 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800915 SLOGE("EVP_EncryptFinal failed\n");
916 return -1;
917 }
918
919 if (encrypted_len + final_len != KEY_LEN_BYTES) {
920 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
921 return -1;
922 } else {
923 return 0;
924 }
925}
926
JP Abgrall7bdfa522013-11-15 13:42:56 -0800927static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
Ken Sumralle8744072011-01-18 22:01:55 -0800928 unsigned char *encrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700929 unsigned char *decrypted_master_key,
930 kdf_func kdf, void *kdf_params)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800931{
932 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 -0800933 EVP_CIPHER_CTX d_ctx;
934 int decrypted_len, final_len;
935
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800936 /* Turn the password into a key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700937 kdf(passwd, salt, ikey, kdf_params);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800938
939 /* Initialize the decryption engine */
940 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
941 return -1;
942 }
943 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
944 /* Decrypt the master key */
945 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
946 encrypted_master_key, KEY_LEN_BYTES)) {
947 return -1;
948 }
949 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
950 return -1;
951 }
952
953 if (decrypted_len + final_len != KEY_LEN_BYTES) {
954 return -1;
955 } else {
956 return 0;
957 }
958}
959
Kenny Rootc4c70f12013-06-14 12:11:38 -0700960static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800961{
Kenny Rootc4c70f12013-06-14 12:11:38 -0700962 if (ftr->kdf_type == KDF_SCRYPT) {
963 *kdf = scrypt;
964 *kdf_params = ftr;
965 } else {
966 *kdf = pbkdf2;
967 *kdf_params = NULL;
968 }
969}
970
JP Abgrall7bdfa522013-11-15 13:42:56 -0800971static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700972 struct crypt_mnt_ftr *crypt_ftr)
973{
974 kdf_func kdf;
975 void *kdf_params;
976 int ret;
977
978 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
JP Abgrall7bdfa522013-11-15 13:42:56 -0800979 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, decrypted_master_key, kdf,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700980 kdf_params);
981 if (ret != 0) {
982 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -0700983 }
984
985 return ret;
986}
987
988static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
989 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800990 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -0800991 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800992 EVP_CIPHER_CTX e_ctx;
993 int encrypted_len, final_len;
994
995 /* Get some random bits for a key */
996 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -0800997 read(fd, key_buf, sizeof(key_buf));
998 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800999 close(fd);
1000
1001 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001002 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001003}
1004
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001005static int wait_and_unmount(char *mountpoint)
1006{
1007 int i, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001008#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001009
1010 /* Now umount the tmpfs filesystem */
1011 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
1012 if (umount(mountpoint)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001013 if (errno == EINVAL) {
1014 /* EINVAL is returned if the directory is not a mountpoint,
1015 * i.e. there is no filesystem mounted there. So just get out.
1016 */
1017 break;
1018 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001019 sleep(1);
1020 i++;
1021 } else {
1022 break;
1023 }
1024 }
1025
1026 if (i < WAIT_UNMOUNT_COUNT) {
1027 SLOGD("unmounting %s succeeded\n", mountpoint);
1028 rc = 0;
1029 } else {
1030 SLOGE("unmounting %s failed\n", mountpoint);
1031 rc = -1;
1032 }
1033
1034 return rc;
1035}
1036
Ken Sumrallc5872692013-05-14 15:26:31 -07001037#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001038static int prep_data_fs(void)
1039{
1040 int i;
1041
1042 /* Do the prep of the /data filesystem */
1043 property_set("vold.post_fs_data_done", "0");
1044 property_set("vold.decrypt", "trigger_post_fs_data");
1045 SLOGD("Just triggered post_fs_data\n");
1046
Ken Sumrallc5872692013-05-14 15:26:31 -07001047 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001048 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001049 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001050
1051 property_get("vold.post_fs_data_done", p, "0");
1052 if (*p == '1') {
1053 break;
1054 } else {
1055 usleep(250000);
1056 }
1057 }
1058 if (i == DATA_PREP_TIMEOUT) {
1059 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001060 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001061 return -1;
1062 } else {
1063 SLOGD("post_fs_data done\n");
1064 return 0;
1065 }
1066}
1067
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001068int cryptfs_restart(void)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001069{
1070 char fs_type[32];
1071 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001072 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001073 char fs_options[256];
1074 unsigned long mnt_flags;
1075 struct stat statbuf;
1076 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001077 static int restart_successful = 0;
1078
1079 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001080 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001081 SLOGE("Encrypted filesystem not validated, aborting");
1082 return -1;
1083 }
1084
1085 if (restart_successful) {
1086 SLOGE("System already restarted with encrypted disk, aborting");
1087 return -1;
1088 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001089
1090 /* Here is where we shut down the framework. The init scripts
1091 * start all services in one of three classes: core, main or late_start.
1092 * On boot, we start core and main. Now, we stop main, but not core,
1093 * as core includes vold and a few other really important things that
1094 * we need to keep running. Once main has stopped, we should be able
1095 * to umount the tmpfs /data, then mount the encrypted /data.
1096 * We then restart the class main, and also the class late_start.
1097 * At the moment, I've only put a few things in late_start that I know
1098 * are not needed to bring up the framework, and that also cause problems
1099 * with unmounting the tmpfs /data, but I hope to add add more services
1100 * to the late_start class as we optimize this to decrease the delay
1101 * till the user is asked for the password to the filesystem.
1102 */
1103
1104 /* The init files are setup to stop the class main when vold.decrypt is
1105 * set to trigger_reset_main.
1106 */
1107 property_set("vold.decrypt", "trigger_reset_main");
1108 SLOGD("Just asked init to shut down class main\n");
1109
Ken Sumrall92736ef2012-10-17 20:57:14 -07001110 /* Ugh, shutting down the framework is not synchronous, so until it
1111 * can be fixed, this horrible hack will wait a moment for it all to
1112 * shut down before proceeding. Without it, some devices cannot
1113 * restart the graphics services.
1114 */
1115 sleep(2);
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001116
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001117 /* Now that the framework is shutdown, we should be able to umount()
1118 * the tmpfs filesystem, and mount the real one.
1119 */
1120
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001121 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1122 if (strlen(crypto_blkdev) == 0) {
1123 SLOGE("fs_crypto_blkdev not set\n");
1124 return -1;
1125 }
1126
Ken Sumralle5032c42012-04-01 23:58:44 -07001127 if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001128 /* If ro.crypto.readonly is set to 1, mount the decrypted
1129 * filesystem readonly. This is used when /data is mounted by
1130 * recovery mode.
1131 */
1132 char ro_prop[PROPERTY_VALUE_MAX];
1133 property_get("ro.crypto.readonly", ro_prop, "");
1134 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1135 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1136 rec->flags |= MS_RDONLY;
1137 }
1138
Ken Sumralle5032c42012-04-01 23:58:44 -07001139 /* If that succeeded, then mount the decrypted filesystem */
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001140 fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001141
Ken Sumralle5032c42012-04-01 23:58:44 -07001142 property_set("vold.decrypt", "trigger_load_persist_props");
1143 /* Create necessary paths on /data */
1144 if (prep_data_fs()) {
1145 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001146 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001147
1148 /* startup service classes main and late_start */
1149 property_set("vold.decrypt", "trigger_restart_framework");
1150 SLOGD("Just triggered restart_framework\n");
1151
1152 /* Give it a few moments to get started */
1153 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001154 }
1155
Ken Sumrall0cc16632011-01-18 20:32:26 -08001156 if (rc == 0) {
1157 restart_successful = 1;
1158 }
1159
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001160 return rc;
1161}
1162
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001163static int do_crypto_complete(char *mount_point)
1164{
1165 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001166 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001167 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001168
1169 property_get("ro.crypto.state", encrypted_state, "");
1170 if (strcmp(encrypted_state, "encrypted") ) {
1171 SLOGE("not running with encryption, aborting");
1172 return 1;
1173 }
1174
Ken Sumrall160b4d62013-04-22 12:15:39 -07001175 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001176 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001177
Ken Sumralle1a45852011-12-14 21:24:27 -08001178 /*
1179 * Only report this error if key_loc is a file and it exists.
1180 * If the device was never encrypted, and /data is not mountable for
1181 * some reason, returning 1 should prevent the UI from presenting the
1182 * a "enter password" screen, or worse, a "press button to wipe the
1183 * device" screen.
1184 */
1185 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1186 SLOGE("master key file does not exist, aborting");
1187 return 1;
1188 } else {
1189 SLOGE("Error getting crypt footer and key\n");
1190 return -1;
1191 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001192 }
1193
1194 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1195 SLOGE("Encryption process didn't finish successfully\n");
1196 return -2; /* -2 is the clue to the UI that there is no usable data on the disk,
1197 * and give the user an option to wipe the disk */
1198 }
1199
1200 /* We passed the test! We shall diminish, and return to the west */
1201 return 0;
1202}
1203
Ken Sumrall29d8da82011-05-18 17:20:07 -07001204static int test_mount_encrypted_fs(char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001205{
1206 struct crypt_mnt_ftr crypt_ftr;
1207 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001208 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001209 char crypto_blkdev[MAXPATHLEN];
1210 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001211 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001212 unsigned int orig_failed_decrypt_count;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001213 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001214 int rc;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001215 kdf_func kdf;
1216 void *kdf_params;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001217
Ken Sumrall0cc16632011-01-18 20:32:26 -08001218 property_get("ro.crypto.state", encrypted_state, "");
Jason parks70a4b3f2011-01-28 10:10:47 -06001219 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001220 SLOGE("encrypted fs already validated or not running with encryption, aborting");
1221 return -1;
1222 }
1223
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001224 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001225
Ken Sumrall160b4d62013-04-22 12:15:39 -07001226 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001227 SLOGE("Error getting crypt footer and key\n");
1228 return -1;
1229 }
Ken Sumralld33d4172011-02-01 00:49:13 -08001230
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001231 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr.fs_size);
1232 orig_failed_decrypt_count = crypt_ftr.failed_decrypt_count;
1233
1234 if (! (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001235 if (decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr)) {
1236 SLOGE("Failed to decrypt master key\n");
1237 return -1;
1238 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001239 }
1240
1241 if (create_crypto_blk_dev(&crypt_ftr, decrypted_master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -07001242 real_blkdev, crypto_blkdev, label)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001243 SLOGE("Error creating decrypted block device\n");
1244 return -1;
1245 }
1246
Alex Klyubin707795a2013-05-10 15:17:07 -07001247 /* If init detects an encrypted filesystem, it writes a file for each such
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001248 * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
1249 * files and passes that data to me */
1250 /* Create a tmp mount point to try mounting the decryptd fs
1251 * Since we're here, the mount_point should be a tmpfs filesystem, so make
1252 * a directory in it to test mount the decrypted filesystem.
1253 */
1254 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1255 mkdir(tmp_mount_point, 0755);
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001256 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001257 SLOGE("Error temp mounting decrypted block device\n");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001258 delete_crypto_blk_dev(label);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001259 crypt_ftr.failed_decrypt_count++;
1260 } else {
1261 /* Success, so just umount and we'll mount it properly when we restart
1262 * the framework.
1263 */
1264 umount(tmp_mount_point);
1265 crypt_ftr.failed_decrypt_count = 0;
1266 }
1267
1268 if (orig_failed_decrypt_count != crypt_ftr.failed_decrypt_count) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001269 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001270 }
1271
1272 if (crypt_ftr.failed_decrypt_count) {
1273 /* We failed to mount the device, so return an error */
1274 rc = crypt_ftr.failed_decrypt_count;
1275
1276 } else {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001277 /* Woot! Success! Save the name of the crypto block device
1278 * so we can mount it when restarting the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001279 */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001280 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001281
1282 /* Also save a the master key so we can reencrypted the key
1283 * the key when we want to change the password on it.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001284 */
Jason parks70a4b3f2011-01-28 10:10:47 -06001285 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001286 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001287 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001288 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001289 rc = 0;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001290 /*
1291 * Upgrade if we're not using the latest KDF.
1292 */
1293 if (crypt_ftr.kdf_type != KDF_SCRYPT) {
1294 crypt_ftr.kdf_type = KDF_SCRYPT;
1295 rc = encrypt_master_key(passwd, crypt_ftr.salt, saved_master_key, crypt_ftr.master_key,
1296 &crypt_ftr);
1297 if (!rc) {
1298 rc = put_crypt_ftr_and_key(&crypt_ftr);
1299 }
1300 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1301 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001302 }
1303
1304 return rc;
1305}
1306
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001307/* Called by vold when it wants to undo the crypto mapping of a volume it
1308 * manages. This is usually in response to a factory reset, when we want
1309 * to undo the crypto mapping so the volume is formatted in the clear.
1310 */
1311int cryptfs_revert_volume(const char *label)
1312{
1313 return delete_crypto_blk_dev((char *)label);
1314}
1315
Ken Sumrall29d8da82011-05-18 17:20:07 -07001316/*
1317 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1318 * Setup a dm-crypt mapping, use the saved master key from
1319 * setting up the /data mapping, and return the new device path.
1320 */
1321int cryptfs_setup_volume(const char *label, int major, int minor,
1322 char *crypto_sys_path, unsigned int max_path,
1323 int *new_major, int *new_minor)
1324{
1325 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1326 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001327 struct stat statbuf;
1328 int nr_sec, fd;
1329
1330 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1331
Ken Sumrall160b4d62013-04-22 12:15:39 -07001332 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001333
1334 /* Update the fs_size field to be the size of the volume */
1335 fd = open(real_blkdev, O_RDONLY);
1336 nr_sec = get_blkdev_size(fd);
1337 close(fd);
1338 if (nr_sec == 0) {
1339 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1340 return -1;
1341 }
1342
1343 sd_crypt_ftr.fs_size = nr_sec;
1344 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1345 crypto_blkdev, label);
1346
1347 stat(crypto_blkdev, &statbuf);
1348 *new_major = MAJOR(statbuf.st_rdev);
1349 *new_minor = MINOR(statbuf.st_rdev);
1350
1351 /* Create path to sys entry for this block device */
1352 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1353
1354 return 0;
1355}
1356
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001357int cryptfs_crypto_complete(void)
1358{
1359 return do_crypto_complete("/data");
1360}
1361
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001362int cryptfs_check_passwd(char *passwd)
1363{
1364 int rc = -1;
1365
Ken Sumrall29d8da82011-05-18 17:20:07 -07001366 rc = test_mount_encrypted_fs(passwd, DATA_MNT_POINT, "userdata");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001367
1368 return rc;
1369}
1370
Ken Sumrall3ad90722011-10-04 20:38:29 -07001371int cryptfs_verify_passwd(char *passwd)
1372{
1373 struct crypt_mnt_ftr crypt_ftr;
1374 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001375 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001376 char encrypted_state[PROPERTY_VALUE_MAX];
1377 int rc;
1378
1379 property_get("ro.crypto.state", encrypted_state, "");
1380 if (strcmp(encrypted_state, "encrypted") ) {
1381 SLOGE("device not encrypted, aborting");
1382 return -2;
1383 }
1384
1385 if (!master_key_saved) {
1386 SLOGE("encrypted fs not yet mounted, aborting");
1387 return -1;
1388 }
1389
1390 if (!saved_mount_point) {
1391 SLOGE("encrypted fs failed to save mount point, aborting");
1392 return -1;
1393 }
1394
Ken Sumrall160b4d62013-04-22 12:15:39 -07001395 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001396 SLOGE("Error getting crypt footer and key\n");
1397 return -1;
1398 }
1399
1400 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1401 /* If the device has no password, then just say the password is valid */
1402 rc = 0;
1403 } else {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001404 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001405 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1406 /* They match, the password is correct */
1407 rc = 0;
1408 } else {
1409 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1410 sleep(1);
1411 rc = 1;
1412 }
1413 }
1414
1415 return rc;
1416}
1417
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001418/* Initialize a crypt_mnt_ftr structure. The keysize is
1419 * defaulted to 16 bytes, and the filesystem size to 0.
1420 * Presumably, at a minimum, the caller will update the
1421 * filesystem size and crypto_type_name after calling this function.
1422 */
1423static void cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
1424{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001425 off64_t off;
1426
1427 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001428 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001429 ftr->major_version = CURRENT_MAJOR_VERSION;
1430 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001431 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001432 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001433
Kenny Rootc4c70f12013-06-14 12:11:38 -07001434 ftr->kdf_type = KDF_SCRYPT;
1435 get_device_scrypt_params(ftr);
1436
Ken Sumrall160b4d62013-04-22 12:15:39 -07001437 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1438 if (get_crypt_ftr_info(NULL, &off) == 0) {
1439 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1440 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1441 ftr->persist_data_size;
1442 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001443}
1444
Ken Sumrall29d8da82011-05-18 17:20:07 -07001445static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001446{
Ken Sumralle550f782013-08-20 13:48:23 -07001447 const char *args[10];
1448 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1449 int num_args;
1450 int status;
1451 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001452 int rc = -1;
1453
Ken Sumrall29d8da82011-05-18 17:20:07 -07001454 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001455 args[0] = "/system/bin/make_ext4fs";
1456 args[1] = "-a";
1457 args[2] = "/data";
1458 args[3] = "-l";
1459 snprintf(size_str, sizeof(size_str), "%lld", size * 512);
1460 args[4] = size_str;
1461 args[5] = crypto_blkdev;
1462 num_args = 6;
1463 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1464 args[0], args[1], args[2], args[3], args[4], args[5]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001465 } else if (type== FAT_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001466 args[0] = "/system/bin/newfs_msdos";
1467 args[1] = "-F";
1468 args[2] = "32";
1469 args[3] = "-O";
1470 args[4] = "android";
1471 args[5] = "-c";
1472 args[6] = "8";
1473 args[7] = "-s";
1474 snprintf(size_str, sizeof(size_str), "%lld", size);
1475 args[8] = size_str;
1476 args[9] = crypto_blkdev;
1477 num_args = 10;
1478 SLOGI("Making empty filesystem with command %s %s %s %s %s %s %s %s %s %s\n",
1479 args[0], args[1], args[2], args[3], args[4], args[5],
1480 args[6], args[7], args[8], args[9]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001481 } else {
1482 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1483 return -1;
1484 }
1485
Ken Sumralle550f782013-08-20 13:48:23 -07001486 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1487
1488 if (tmp != 0) {
1489 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001490 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07001491 if (WIFEXITED(status)) {
1492 if (WEXITSTATUS(status)) {
1493 SLOGE("Error creating filesystem on %s, exit status %d ",
1494 crypto_blkdev, WEXITSTATUS(status));
1495 } else {
1496 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
1497 rc = 0;
1498 }
1499 } else {
1500 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
1501 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001502 }
1503
1504 return rc;
1505}
1506
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001507#define CRYPT_INPLACE_BUFSIZE 4096
1508#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / 512)
Ken Sumrall29d8da82011-05-18 17:20:07 -07001509static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev, off64_t size,
1510 off64_t *size_already_done, off64_t tot_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001511{
1512 int realfd, cryptofd;
1513 char *buf[CRYPT_INPLACE_BUFSIZE];
1514 int rc = -1;
1515 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001516 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001517 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001518
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001519 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
1520 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
1521 return -1;
1522 }
1523
1524 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
1525 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1526 close(realfd);
1527 return -1;
1528 }
1529
1530 /* This is pretty much a simple loop of reading 4K, and writing 4K.
1531 * The size passed in is the number of 512 byte sectors in the filesystem.
1532 * So compute the number of whole 4K blocks we should read/write,
1533 * and the remainder.
1534 */
1535 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
1536 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001537 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
1538 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001539
1540 SLOGE("Encrypting filesystem in place...");
1541
Ken Sumrall29d8da82011-05-18 17:20:07 -07001542 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001543 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001544 /* process the majority of the filesystem in blocks */
1545 for (i=0; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001546 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001547 if (new_pct > cur_pct) {
1548 char buf[8];
1549
1550 cur_pct = new_pct;
1551 snprintf(buf, sizeof(buf), "%lld", cur_pct);
1552 property_set("vold.encrypt_progress", buf);
1553 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001554 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1555 SLOGE("Error reading real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1556 goto errout;
1557 }
1558 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1559 SLOGE("Error writing crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1560 goto errout;
1561 }
1562 }
1563
1564 /* Do any remaining sectors */
1565 for (i=0; i<remainder; i++) {
1566 if (unix_read(realfd, buf, 512) <= 0) {
1567 SLOGE("Error reading rival sectors from real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1568 goto errout;
1569 }
1570 if (unix_write(cryptofd, buf, 512) <= 0) {
1571 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1572 goto errout;
1573 }
1574 }
1575
Ken Sumrall29d8da82011-05-18 17:20:07 -07001576 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001577 rc = 0;
1578
1579errout:
1580 close(realfd);
1581 close(cryptofd);
1582
1583 return rc;
1584}
1585
1586#define CRYPTO_ENABLE_WIPE 1
1587#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001588
1589#define FRAMEWORK_BOOT_WAIT 60
1590
Ken Sumrall29d8da82011-05-18 17:20:07 -07001591static inline int should_encrypt(struct volume_info *volume)
1592{
1593 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
1594 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
1595}
1596
JP Abgrall502dc742013-11-01 13:06:20 -07001597int cryptfs_enable(char *howarg, char *passwd, int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001598{
1599 int how = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001600 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN], sd_crypto_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07001601 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001602 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07001603 int rc=-1, fd, i, ret;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001604 struct crypt_mnt_ftr crypt_ftr, sd_crypt_ftr;;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001605 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001606 char tmpfs_options[PROPERTY_VALUE_MAX];
1607 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001608 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07001609 char key_loc[PROPERTY_VALUE_MAX];
1610 char fuse_sdcard[PROPERTY_VALUE_MAX];
1611 char *sd_mnt_point;
1612 char sd_blk_dev[256] = { 0 };
1613 int num_vols;
1614 struct volume_info *vol_list = 0;
1615 off64_t cur_encryption_done=0, tot_encryption_size=0;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001616
1617 property_get("ro.crypto.state", encrypted_state, "");
JP Abgrall502dc742013-11-01 13:06:20 -07001618 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001619 SLOGE("Device is already running encrypted, aborting");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001620 goto error_unencrypted;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001621 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001622
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001623 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001624
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001625 if (!strcmp(howarg, "wipe")) {
1626 how = CRYPTO_ENABLE_WIPE;
1627 } else if (! strcmp(howarg, "inplace")) {
1628 how = CRYPTO_ENABLE_INPLACE;
1629 } else {
1630 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08001631 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001632 }
1633
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001634 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001635
Ken Sumrall3ed82362011-01-28 23:31:16 -08001636 /* Get the size of the real block device */
1637 fd = open(real_blkdev, O_RDONLY);
1638 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
1639 SLOGE("Cannot get size of block device %s\n", real_blkdev);
1640 goto error_unencrypted;
1641 }
1642 close(fd);
1643
1644 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001645 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001646 unsigned int fs_size_sec, max_fs_size_sec;
1647
1648 fs_size_sec = get_fs_size(real_blkdev);
1649 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1650
1651 if (fs_size_sec > max_fs_size_sec) {
1652 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
1653 goto error_unencrypted;
1654 }
1655 }
1656
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001657 /* Get a wakelock as this may take a while, and we don't want the
1658 * device to sleep on us. We'll grab a partial wakelock, and if the UI
1659 * wants to keep the screen on, it can grab a full wakelock.
1660 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001661 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001662 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
1663
Jeff Sharkey7382f812012-08-23 14:08:59 -07001664 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07001665 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07001666 if (!sd_mnt_point) {
1667 sd_mnt_point = getenv("EXTERNAL_STORAGE");
1668 }
1669 if (!sd_mnt_point) {
1670 sd_mnt_point = "/mnt/sdcard";
1671 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07001672
1673 num_vols=vold_getNumDirectVolumes();
1674 vol_list = malloc(sizeof(struct volume_info) * num_vols);
1675 vold_getDirectVolumeList(vol_list);
1676
1677 for (i=0; i<num_vols; i++) {
1678 if (should_encrypt(&vol_list[i])) {
1679 fd = open(vol_list[i].blk_dev, O_RDONLY);
1680 if ( (vol_list[i].size = get_blkdev_size(fd)) == 0) {
1681 SLOGE("Cannot get size of block device %s\n", vol_list[i].blk_dev);
1682 goto error_unencrypted;
1683 }
1684 close(fd);
1685
Ken Sumrall3b170052011-07-11 15:38:57 -07001686 ret=vold_disableVol(vol_list[i].label);
Ken Sumrall319b1042011-06-14 14:01:55 -07001687 if ((ret < 0) && (ret != UNMOUNT_NOT_MOUNTED_ERR)) {
1688 /* -2 is returned when the device exists but is not currently mounted.
1689 * ignore the error and continue. */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001690 SLOGE("Failed to unmount volume %s\n", vol_list[i].label);
1691 goto error_unencrypted;
1692 }
1693 }
1694 }
1695
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001696 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001697 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001698 */
1699 property_set("vold.decrypt", "trigger_shutdown_framework");
1700 SLOGD("Just asked init to shut down class main\n");
1701
Ken Sumrall425524d2012-06-14 20:55:28 -07001702 if (vold_unmountAllAsecs()) {
1703 /* Just report the error. If any are left mounted,
1704 * umounting /data below will fail and handle the error.
1705 */
1706 SLOGE("Error unmounting internal asecs");
1707 }
1708
Ken Sumrall29d8da82011-05-18 17:20:07 -07001709 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
1710 if (!strcmp(fuse_sdcard, "true")) {
1711 /* This is a device using the fuse layer to emulate the sdcard semantics
1712 * on top of the userdata partition. vold does not manage it, it is managed
1713 * by the sdcard service. The sdcard service was killed by the property trigger
1714 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
1715 * unlike the case for vold managed devices above.
1716 */
1717 if (wait_and_unmount(sd_mnt_point)) {
1718 goto error_shutting_down;
1719 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001720 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001721
1722 /* Now unmount the /data partition. */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001723 if (wait_and_unmount(DATA_MNT_POINT)) {
JP Abgrall502dc742013-11-01 13:06:20 -07001724 if (allow_reboot) {
1725 goto error_shutting_down;
1726 } else {
1727 goto error_unencrypted;
1728 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001729 }
1730
1731 /* Do extra work for a better UX when doing the long inplace encryption */
1732 if (how == CRYPTO_ENABLE_INPLACE) {
1733 /* Now that /data is unmounted, we need to mount a tmpfs
1734 * /data, set a property saying we're doing inplace encryption,
1735 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001736 */
Ken Sumralle5032c42012-04-01 23:58:44 -07001737 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001738 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001739 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001740 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08001741 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001742
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001743 /* restart the framework. */
1744 /* Create necessary paths on /data */
1745 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001746 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001747 }
1748
Ken Sumrall92736ef2012-10-17 20:57:14 -07001749 /* Ugh, shutting down the framework is not synchronous, so until it
1750 * can be fixed, this horrible hack will wait a moment for it all to
1751 * shut down before proceeding. Without it, some devices cannot
1752 * restart the graphics services.
1753 */
1754 sleep(2);
1755
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001756 /* startup service classes main and late_start */
1757 property_set("vold.decrypt", "trigger_restart_min_framework");
1758 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001759
Ken Sumrall7df84122011-01-18 14:04:08 -08001760 /* OK, the framework is restarted and will soon be showing a
1761 * progress bar. Time to setup an encrypted mapping, and
1762 * either write a new filesystem, or encrypt in place updating
1763 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001764 */
1765 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001766
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001767 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001768 /* Initialize a crypt_mnt_ftr for the partition */
1769 cryptfs_init_crypt_mnt_ftr(&crypt_ftr);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001770
Ken Sumrall29d8da82011-05-18 17:20:07 -07001771 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
1772 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1773 } else {
1774 crypt_ftr.fs_size = nr_sec;
1775 }
Ken Sumralld33d4172011-02-01 00:49:13 -08001776 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001777 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
1778
1779 /* Make an encrypted master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001780 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001781 SLOGE("Cannot create encrypted master key\n");
JP Abgrall502dc742013-11-01 13:06:20 -07001782 goto error_shutting_down;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001783 }
1784
1785 /* Write the key to the end of the partition */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001786 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001787
Ken Sumrall160b4d62013-04-22 12:15:39 -07001788 /* If any persistent data has been remembered, save it.
1789 * If none, create a valid empty table and save that.
1790 */
1791 if (!persist_data) {
1792 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
1793 if (pdata) {
1794 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
1795 persist_data = pdata;
1796 }
1797 }
1798 if (persist_data) {
1799 save_persistent_data();
1800 }
1801
JP Abgrall7bdfa522013-11-15 13:42:56 -08001802 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001803 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
1804 "userdata");
1805
Ken Sumrall128626f2011-06-28 18:45:14 -07001806 /* The size of the userdata partition, and add in the vold volumes below */
1807 tot_encryption_size = crypt_ftr.fs_size;
1808
Ken Sumrall29d8da82011-05-18 17:20:07 -07001809 /* setup crypto mapping for all encryptable volumes handled by vold */
1810 for (i=0; i<num_vols; i++) {
1811 if (should_encrypt(&vol_list[i])) {
1812 vol_list[i].crypt_ftr = crypt_ftr; /* gotta love struct assign */
1813 vol_list[i].crypt_ftr.fs_size = vol_list[i].size;
1814 create_crypto_blk_dev(&vol_list[i].crypt_ftr, decrypted_master_key,
1815 vol_list[i].blk_dev, vol_list[i].crypto_blkdev,
1816 vol_list[i].label);
Ken Sumrall128626f2011-06-28 18:45:14 -07001817 tot_encryption_size += vol_list[i].size;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001818 }
1819 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001820
1821 if (how == CRYPTO_ENABLE_WIPE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001822 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr.fs_size, EXT4_FS);
1823 /* Encrypt all encryptable volumes handled by vold */
1824 if (!rc) {
1825 for (i=0; i<num_vols; i++) {
1826 if (should_encrypt(&vol_list[i])) {
1827 rc = cryptfs_enable_wipe(vol_list[i].crypto_blkdev,
1828 vol_list[i].crypt_ftr.fs_size, FAT_FS);
1829 }
1830 }
1831 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001832 } else if (how == CRYPTO_ENABLE_INPLACE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001833 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr.fs_size,
1834 &cur_encryption_done, tot_encryption_size);
1835 /* Encrypt all encryptable volumes handled by vold */
1836 if (!rc) {
1837 for (i=0; i<num_vols; i++) {
1838 if (should_encrypt(&vol_list[i])) {
1839 rc = cryptfs_enable_inplace(vol_list[i].crypto_blkdev,
1840 vol_list[i].blk_dev,
1841 vol_list[i].crypt_ftr.fs_size,
1842 &cur_encryption_done, tot_encryption_size);
1843 }
1844 }
1845 }
1846 if (!rc) {
1847 /* The inplace routine never actually sets the progress to 100%
1848 * due to the round down nature of integer division, so set it here */
1849 property_set("vold.encrypt_progress", "100");
1850 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001851 } else {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001852 /* Shouldn't happen */
1853 SLOGE("cryptfs_enable: internal error, unknown option\n");
JP Abgrall502dc742013-11-01 13:06:20 -07001854 goto error_shutting_down;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001855 }
1856
1857 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001858 delete_crypto_blk_dev("userdata");
1859 for (i=0; i<num_vols; i++) {
1860 if (should_encrypt(&vol_list[i])) {
1861 delete_crypto_blk_dev(vol_list[i].label);
1862 }
1863 }
1864
1865 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001866
1867 if (! rc) {
1868 /* Success */
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001869
Ken Sumralld33d4172011-02-01 00:49:13 -08001870 /* Clear the encryption in progres flag in the footer */
1871 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001872 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08001873
Ken Sumrall29d8da82011-05-18 17:20:07 -07001874 sleep(2); /* Give the UI a chance to show 100% progress */
Ken Sumralladfba362013-06-04 16:37:52 -07001875 cryptfs_reboot(0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001876 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001877 char value[PROPERTY_VALUE_MAX];
1878
Ken Sumrall319369a2012-06-27 16:30:18 -07001879 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001880 if (!strcmp(value, "1")) {
1881 /* wipe data if encryption failed */
1882 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
1883 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07001884 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001885 if (fd >= 0) {
1886 write(fd, "--wipe_data", strlen("--wipe_data") + 1);
1887 close(fd);
1888 } else {
1889 SLOGE("could not open /cache/recovery/command\n");
1890 }
Ken Sumralladfba362013-06-04 16:37:52 -07001891 cryptfs_reboot(1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001892 } else {
1893 /* set property to trigger dialog */
1894 property_set("vold.encrypt_progress", "error_partially_encrypted");
1895 release_wake_lock(lockid);
1896 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001897 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001898 }
1899
Ken Sumrall3ed82362011-01-28 23:31:16 -08001900 /* hrm, the encrypt step claims success, but the reboot failed.
1901 * This should not happen.
1902 * Set the property and return. Hope the framework can deal with it.
1903 */
1904 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001905 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001906 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08001907
1908error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07001909 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001910 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001911 if (lockid[0]) {
1912 release_wake_lock(lockid);
1913 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001914 return -1;
1915
1916error_shutting_down:
1917 /* we failed, and have not encrypted anthing, so the users's data is still intact,
1918 * but the framework is stopped and not restarted to show the error, so it's up to
1919 * vold to restart the system.
1920 */
1921 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Ken Sumralladfba362013-06-04 16:37:52 -07001922 cryptfs_reboot(0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001923
1924 /* shouldn't get here */
1925 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001926 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001927 if (lockid[0]) {
1928 release_wake_lock(lockid);
1929 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001930 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001931}
1932
Jason parks70a4b3f2011-01-28 10:10:47 -06001933int cryptfs_changepw(char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001934{
1935 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001936 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001937
1938 /* This is only allowed after we've successfully decrypted the master key */
Jason parks70a4b3f2011-01-28 10:10:47 -06001939 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001940 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001941 return -1;
1942 }
1943
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001944 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001945 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall57b63e62011-01-17 18:29:19 -08001946 SLOGE("Error getting crypt footer and key");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001947 return -1;
1948 }
1949
Kenny Rootc4c70f12013-06-14 12:11:38 -07001950 encrypt_master_key(newpw, crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001951
Jason parks70a4b3f2011-01-28 10:10:47 -06001952 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001953 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001954
1955 return 0;
1956}
Ken Sumrall160b4d62013-04-22 12:15:39 -07001957
1958static int persist_get_key(char *fieldname, char *value)
1959{
1960 unsigned int i;
1961
1962 if (persist_data == NULL) {
1963 return -1;
1964 }
1965 for (i = 0; i < persist_data->persist_valid_entries; i++) {
1966 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
1967 /* We found it! */
1968 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
1969 return 0;
1970 }
1971 }
1972
1973 return -1;
1974}
1975
1976static int persist_set_key(char *fieldname, char *value, int encrypted)
1977{
1978 unsigned int i;
1979 unsigned int num;
1980 struct crypt_mnt_ftr crypt_ftr;
1981 unsigned int max_persistent_entries;
1982 unsigned int dsize;
1983
1984 if (persist_data == NULL) {
1985 return -1;
1986 }
1987
1988 /* If encrypted, use the values from the crypt_ftr, otherwise
1989 * use the values for the current spec.
1990 */
1991 if (encrypted) {
1992 if(get_crypt_ftr_and_key(&crypt_ftr)) {
1993 return -1;
1994 }
1995 dsize = crypt_ftr.persist_data_size;
1996 } else {
1997 dsize = CRYPT_PERSIST_DATA_SIZE;
1998 }
1999 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2000 sizeof(struct crypt_persist_entry);
2001
2002 num = persist_data->persist_valid_entries;
2003
2004 for (i = 0; i < num; i++) {
2005 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2006 /* We found an existing entry, update it! */
2007 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2008 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2009 return 0;
2010 }
2011 }
2012
2013 /* We didn't find it, add it to the end, if there is room */
2014 if (persist_data->persist_valid_entries < max_persistent_entries) {
2015 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2016 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2017 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2018 persist_data->persist_valid_entries++;
2019 return 0;
2020 }
2021
2022 return -1;
2023}
2024
2025/* Return the value of the specified field. */
2026int cryptfs_getfield(char *fieldname, char *value, int len)
2027{
2028 char temp_value[PROPERTY_VALUE_MAX];
2029 char real_blkdev[MAXPATHLEN];
2030 /* 0 is success, 1 is not encrypted,
2031 * -1 is value not set, -2 is any other error
2032 */
2033 int rc = -2;
2034
2035 if (persist_data == NULL) {
2036 load_persistent_data();
2037 if (persist_data == NULL) {
2038 SLOGE("Getfield error, cannot load persistent data");
2039 goto out;
2040 }
2041 }
2042
2043 if (!persist_get_key(fieldname, temp_value)) {
2044 /* We found it, copy it to the caller's buffer and return */
2045 strlcpy(value, temp_value, len);
2046 rc = 0;
2047 } else {
2048 /* Sadness, it's not there. Return the error */
2049 rc = -1;
2050 }
2051
2052out:
2053 return rc;
2054}
2055
2056/* Set the value of the specified field. */
2057int cryptfs_setfield(char *fieldname, char *value)
2058{
2059 struct crypt_persist_data stored_pdata;
2060 struct crypt_persist_data *pdata_p;
2061 struct crypt_mnt_ftr crypt_ftr;
2062 char encrypted_state[PROPERTY_VALUE_MAX];
2063 /* 0 is success, -1 is an error */
2064 int rc = -1;
2065 int encrypted = 0;
2066
2067 if (persist_data == NULL) {
2068 load_persistent_data();
2069 if (persist_data == NULL) {
2070 SLOGE("Setfield error, cannot load persistent data");
2071 goto out;
2072 }
2073 }
2074
2075 property_get("ro.crypto.state", encrypted_state, "");
2076 if (!strcmp(encrypted_state, "encrypted") ) {
2077 encrypted = 1;
2078 }
2079
2080 if (persist_set_key(fieldname, value, encrypted)) {
2081 goto out;
2082 }
2083
2084 /* If we are running encrypted, save the persistent data now */
2085 if (encrypted) {
2086 if (save_persistent_data()) {
2087 SLOGE("Setfield error, cannot save persistent data");
2088 goto out;
2089 }
2090 }
2091
2092 rc = 0;
2093
2094out:
2095 return rc;
2096}