blob: a742a6350d7e88714f9311eeab6ec3f7a5f80e60 [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)) {
Colin Cross59846b62014-02-06 20:34:29 -0800279 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800280 goto errout;
281 }
282 }
283
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800284 /* Success! */
285 rc = 0;
286
287errout:
288 close(fd);
289 return rc;
290
291}
292
Ken Sumrall160b4d62013-04-22 12:15:39 -0700293static inline int unix_read(int fd, void* buff, int len)
294{
295 return TEMP_FAILURE_RETRY(read(fd, buff, len));
296}
297
298static inline int unix_write(int fd, const void* buff, int len)
299{
300 return TEMP_FAILURE_RETRY(write(fd, buff, len));
301}
302
303static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
304{
305 memset(pdata, 0, len);
306 pdata->persist_magic = PERSIST_DATA_MAGIC;
307 pdata->persist_valid_entries = 0;
308}
309
310/* A routine to update the passed in crypt_ftr to the lastest version.
311 * fd is open read/write on the device that holds the crypto footer and persistent
312 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
313 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
314 */
315static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
316{
Kenny Root7434b312013-06-14 11:29:53 -0700317 int orig_major = crypt_ftr->major_version;
318 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700319
Kenny Root7434b312013-06-14 11:29:53 -0700320 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
321 struct crypt_persist_data *pdata;
322 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700323
Kenny Rootc4c70f12013-06-14 12:11:38 -0700324 SLOGW("upgrading crypto footer to 1.1");
325
Kenny Root7434b312013-06-14 11:29:53 -0700326 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
327 if (pdata == NULL) {
328 SLOGE("Cannot allocate persisent data\n");
329 return;
330 }
331 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
332
333 /* Need to initialize the persistent data area */
334 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
335 SLOGE("Cannot seek to persisent data offset\n");
336 return;
337 }
338 /* Write all zeros to the first copy, making it invalid */
339 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
340
341 /* Write a valid but empty structure to the second copy */
342 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
343 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
344
345 /* Update the footer */
346 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
347 crypt_ftr->persist_data_offset[0] = pdata_offset;
348 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
349 crypt_ftr->minor_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700350 }
351
Kenny Rootc4c70f12013-06-14 12:11:38 -0700352 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version)) {
353 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800354 /* But keep the old kdf_type.
355 * It will get updated later to KDF_SCRYPT after the password has been verified.
356 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700357 crypt_ftr->kdf_type = KDF_PBKDF2;
358 get_device_scrypt_params(crypt_ftr);
359 crypt_ftr->minor_version = 2;
360 }
361
Kenny Root7434b312013-06-14 11:29:53 -0700362 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
363 if (lseek64(fd, offset, SEEK_SET) == -1) {
364 SLOGE("Cannot seek to crypt footer\n");
365 return;
366 }
367 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700368 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700369}
370
371
372static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800373{
374 int fd;
375 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700376 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800377 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700378 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700379 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800380
Ken Sumrall160b4d62013-04-22 12:15:39 -0700381 if (get_crypt_ftr_info(&fname, &starting_off)) {
382 SLOGE("Unable to get crypt_ftr_info\n");
383 return -1;
384 }
385 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700386 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700387 return -1;
388 }
389 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700390 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700391 return -1;
392 }
393
394 /* Make sure it's 16 Kbytes in length */
395 fstat(fd, &statbuf);
396 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
397 SLOGE("footer file %s is not the expected size!\n", fname);
398 goto errout;
399 }
400
401 /* Seek to the start of the crypt footer */
402 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
403 SLOGE("Cannot seek to real block device footer\n");
404 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800405 }
406
407 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
408 SLOGE("Cannot read real block device footer\n");
409 goto errout;
410 }
411
412 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700413 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800414 goto errout;
415 }
416
Kenny Rootc96a5f82013-06-14 12:08:28 -0700417 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
418 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
419 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800420 goto errout;
421 }
422
Kenny Rootc96a5f82013-06-14 12:08:28 -0700423 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
424 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
425 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800426 }
427
Ken Sumrall160b4d62013-04-22 12:15:39 -0700428 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
429 * copy on disk before returning.
430 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700431 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700432 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800433 }
434
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800435 /* Success! */
436 rc = 0;
437
438errout:
439 close(fd);
440 return rc;
441}
442
Ken Sumrall160b4d62013-04-22 12:15:39 -0700443static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
444{
445 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
446 crypt_ftr->persist_data_offset[1]) {
447 SLOGE("Crypt_ftr persist data regions overlap");
448 return -1;
449 }
450
451 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
452 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
453 return -1;
454 }
455
456 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
457 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
458 CRYPT_FOOTER_OFFSET) {
459 SLOGE("Persistent data extends past crypto footer");
460 return -1;
461 }
462
463 return 0;
464}
465
466static int load_persistent_data(void)
467{
468 struct crypt_mnt_ftr crypt_ftr;
469 struct crypt_persist_data *pdata = NULL;
470 char encrypted_state[PROPERTY_VALUE_MAX];
471 char *fname;
472 int found = 0;
473 int fd;
474 int ret;
475 int i;
476
477 if (persist_data) {
478 /* Nothing to do, we've already loaded or initialized it */
479 return 0;
480 }
481
482
483 /* If not encrypted, just allocate an empty table and initialize it */
484 property_get("ro.crypto.state", encrypted_state, "");
485 if (strcmp(encrypted_state, "encrypted") ) {
486 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
487 if (pdata) {
488 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
489 persist_data = pdata;
490 return 0;
491 }
492 return -1;
493 }
494
495 if(get_crypt_ftr_and_key(&crypt_ftr)) {
496 return -1;
497 }
498
499 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
500 SLOGE("Crypt_ftr version doesn't support persistent data");
501 return -1;
502 }
503
504 if (get_crypt_ftr_info(&fname, NULL)) {
505 return -1;
506 }
507
508 ret = validate_persistent_data_storage(&crypt_ftr);
509 if (ret) {
510 return -1;
511 }
512
513 fd = open(fname, O_RDONLY);
514 if (fd < 0) {
515 SLOGE("Cannot open %s metadata file", fname);
516 return -1;
517 }
518
519 if (persist_data == NULL) {
520 pdata = malloc(crypt_ftr.persist_data_size);
521 if (pdata == NULL) {
522 SLOGE("Cannot allocate memory for persistent data");
523 goto err;
524 }
525 }
526
527 for (i = 0; i < 2; i++) {
528 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
529 SLOGE("Cannot seek to read persistent data on %s", fname);
530 goto err2;
531 }
532 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
533 SLOGE("Error reading persistent data on iteration %d", i);
534 goto err2;
535 }
536 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
537 found = 1;
538 break;
539 }
540 }
541
542 if (!found) {
543 SLOGI("Could not find valid persistent data, creating");
544 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
545 }
546
547 /* Success */
548 persist_data = pdata;
549 close(fd);
550 return 0;
551
552err2:
553 free(pdata);
554
555err:
556 close(fd);
557 return -1;
558}
559
560static int save_persistent_data(void)
561{
562 struct crypt_mnt_ftr crypt_ftr;
563 struct crypt_persist_data *pdata;
564 char *fname;
565 off64_t write_offset;
566 off64_t erase_offset;
567 int found = 0;
568 int fd;
569 int ret;
570
571 if (persist_data == NULL) {
572 SLOGE("No persistent data to save");
573 return -1;
574 }
575
576 if(get_crypt_ftr_and_key(&crypt_ftr)) {
577 return -1;
578 }
579
580 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
581 SLOGE("Crypt_ftr version doesn't support persistent data");
582 return -1;
583 }
584
585 ret = validate_persistent_data_storage(&crypt_ftr);
586 if (ret) {
587 return -1;
588 }
589
590 if (get_crypt_ftr_info(&fname, NULL)) {
591 return -1;
592 }
593
594 fd = open(fname, O_RDWR);
595 if (fd < 0) {
596 SLOGE("Cannot open %s metadata file", fname);
597 return -1;
598 }
599
600 pdata = malloc(crypt_ftr.persist_data_size);
601 if (pdata == NULL) {
602 SLOGE("Cannot allocate persistant data");
603 goto err;
604 }
605
606 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
607 SLOGE("Cannot seek to read persistent data on %s", fname);
608 goto err2;
609 }
610
611 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
612 SLOGE("Error reading persistent data before save");
613 goto err2;
614 }
615
616 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
617 /* The first copy is the curent valid copy, so write to
618 * the second copy and erase this one */
619 write_offset = crypt_ftr.persist_data_offset[1];
620 erase_offset = crypt_ftr.persist_data_offset[0];
621 } else {
622 /* The second copy must be the valid copy, so write to
623 * the first copy, and erase the second */
624 write_offset = crypt_ftr.persist_data_offset[0];
625 erase_offset = crypt_ftr.persist_data_offset[1];
626 }
627
628 /* Write the new copy first, if successful, then erase the old copy */
629 if (lseek(fd, write_offset, SEEK_SET) < 0) {
630 SLOGE("Cannot seek to write persistent data");
631 goto err2;
632 }
633 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
634 (int) crypt_ftr.persist_data_size) {
635 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
636 SLOGE("Cannot seek to erase previous persistent data");
637 goto err2;
638 }
639 fsync(fd);
640 memset(pdata, 0, crypt_ftr.persist_data_size);
641 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
642 (int) crypt_ftr.persist_data_size) {
643 SLOGE("Cannot write to erase previous persistent data");
644 goto err2;
645 }
646 fsync(fd);
647 } else {
648 SLOGE("Cannot write to save persistent data");
649 goto err2;
650 }
651
652 /* Success */
653 free(pdata);
654 close(fd);
655 return 0;
656
657err2:
658 free(pdata);
659err:
660 close(fd);
661 return -1;
662}
663
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800664/* Convert a binary key of specified length into an ascii hex string equivalent,
665 * without the leading 0x and with null termination
666 */
667void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
668 char *master_key_ascii)
669{
670 unsigned int i, a;
671 unsigned char nibble;
672
673 for (i=0, a=0; i<keysize; i++, a+=2) {
674 /* For each byte, write out two ascii hex digits */
675 nibble = (master_key[i] >> 4) & 0xf;
676 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
677
678 nibble = master_key[i] & 0xf;
679 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
680 }
681
682 /* Add the null termination */
683 master_key_ascii[a] = '\0';
684
685}
686
Ken Sumralldb5e0262013-02-05 17:39:48 -0800687static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
688 char *real_blk_name, const char *name, int fd,
689 char *extra_params)
690{
691 char buffer[DM_CRYPT_BUF_SIZE];
692 struct dm_ioctl *io;
693 struct dm_target_spec *tgt;
694 char *crypt_params;
695 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
696 int i;
697
698 io = (struct dm_ioctl *) buffer;
699
700 /* Load the mapping table for this device */
701 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
702
703 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
704 io->target_count = 1;
705 tgt->status = 0;
706 tgt->sector_start = 0;
707 tgt->length = crypt_ftr->fs_size;
708 strcpy(tgt->target_type, "crypt");
709
710 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
711 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
712 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
713 master_key_ascii, real_blk_name, extra_params);
714 crypt_params += strlen(crypt_params) + 1;
715 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
716 tgt->next = crypt_params - buffer;
717
718 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
719 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
720 break;
721 }
722 usleep(500000);
723 }
724
725 if (i == TABLE_LOAD_RETRIES) {
726 /* We failed to load the table, return an error */
727 return -1;
728 } else {
729 return i + 1;
730 }
731}
732
733
734static int get_dm_crypt_version(int fd, const char *name, int *version)
735{
736 char buffer[DM_CRYPT_BUF_SIZE];
737 struct dm_ioctl *io;
738 struct dm_target_versions *v;
739 int i;
740
741 io = (struct dm_ioctl *) buffer;
742
743 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
744
745 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
746 return -1;
747 }
748
749 /* Iterate over the returned versions, looking for name of "crypt".
750 * When found, get and return the version.
751 */
752 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
753 while (v->next) {
754 if (! strcmp(v->name, "crypt")) {
755 /* We found the crypt driver, return the version, and get out */
756 version[0] = v->version[0];
757 version[1] = v->version[1];
758 version[2] = v->version[2];
759 return 0;
760 }
761 v = (struct dm_target_versions *)(((char *)v) + v->next);
762 }
763
764 return -1;
765}
766
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800767static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -0700768 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800769{
770 char buffer[DM_CRYPT_BUF_SIZE];
771 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
772 char *crypt_params;
773 struct dm_ioctl *io;
774 struct dm_target_spec *tgt;
775 unsigned int minor;
776 int fd;
Ken Sumralle919efe2012-09-29 17:07:41 -0700777 int i;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800778 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800779 int version[3];
780 char *extra_params;
781 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800782
783 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
784 SLOGE("Cannot open device-mapper\n");
785 goto errout;
786 }
787
788 io = (struct dm_ioctl *) buffer;
789
790 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
791 if (ioctl(fd, DM_DEV_CREATE, io)) {
792 SLOGE("Cannot create dm-crypt device\n");
793 goto errout;
794 }
795
796 /* Get the device status, in particular, the name of it's device file */
797 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
798 if (ioctl(fd, DM_DEV_STATUS, io)) {
799 SLOGE("Cannot retrieve dm-crypt device status\n");
800 goto errout;
801 }
802 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
803 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
804
Ken Sumralldb5e0262013-02-05 17:39:48 -0800805 extra_params = "";
806 if (! get_dm_crypt_version(fd, name, version)) {
807 /* Support for allow_discards was added in version 1.11.0 */
808 if ((version[0] >= 2) ||
809 ((version[0] == 1) && (version[1] >= 11))) {
810 extra_params = "1 allow_discards";
811 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
812 }
Ken Sumralle919efe2012-09-29 17:07:41 -0700813 }
814
Ken Sumralldb5e0262013-02-05 17:39:48 -0800815 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
816 fd, extra_params);
817 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800818 SLOGE("Cannot load dm-crypt mapping table.\n");
819 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800820 } else if (load_count > 1) {
821 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800822 }
823
824 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -0800825 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800826
827 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
828 SLOGE("Cannot resume the dm-crypt device\n");
829 goto errout;
830 }
831
832 /* We made it here with no errors. Woot! */
833 retval = 0;
834
835errout:
836 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
837
838 return retval;
839}
840
Ken Sumrall29d8da82011-05-18 17:20:07 -0700841static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800842{
843 int fd;
844 char buffer[DM_CRYPT_BUF_SIZE];
845 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800846 int retval = -1;
847
848 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
849 SLOGE("Cannot open device-mapper\n");
850 goto errout;
851 }
852
853 io = (struct dm_ioctl *) buffer;
854
855 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
856 if (ioctl(fd, DM_DEV_REMOVE, io)) {
857 SLOGE("Cannot remove dm-crypt device\n");
858 goto errout;
859 }
860
861 /* We made it here with no errors. Woot! */
862 retval = 0;
863
864errout:
865 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
866
867 return retval;
868
869}
870
Kenny Rootc4c70f12013-06-14 12:11:38 -0700871static void pbkdf2(char *passwd, unsigned char *salt, unsigned char *ikey, void *params) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800872 /* Turn the password into a key and IV that can decrypt the master key */
Ken Sumralle8744072011-01-18 22:01:55 -0800873 PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800874 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800875}
876
Kenny Rootc4c70f12013-06-14 12:11:38 -0700877static void scrypt(char *passwd, unsigned char *salt, unsigned char *ikey, void *params) {
878 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
879
880 int N = 1 << ftr->N_factor;
881 int r = 1 << ftr->r_factor;
882 int p = 1 << ftr->p_factor;
883
884 /* Turn the password into a key and IV that can decrypt the master key */
885 crypto_scrypt((unsigned char *) passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
886 KEY_LEN_BYTES + IV_LEN_BYTES);
887}
888
Ken Sumralle8744072011-01-18 22:01:55 -0800889static int encrypt_master_key(char *passwd, unsigned char *salt,
890 unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700891 unsigned char *encrypted_master_key,
892 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800893{
894 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
895 EVP_CIPHER_CTX e_ctx;
896 int encrypted_len, final_len;
897
898 /* Turn the password into a key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700899 get_device_scrypt_params(crypt_ftr);
900 scrypt(passwd, salt, ikey, crypt_ftr);
901
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800902 /* Initialize the decryption engine */
903 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
904 SLOGE("EVP_EncryptInit failed\n");
905 return -1;
906 }
907 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800908
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800909 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800910 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
911 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800912 SLOGE("EVP_EncryptUpdate failed\n");
913 return -1;
914 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800915 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800916 SLOGE("EVP_EncryptFinal failed\n");
917 return -1;
918 }
919
920 if (encrypted_len + final_len != KEY_LEN_BYTES) {
921 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
922 return -1;
923 } else {
924 return 0;
925 }
926}
927
JP Abgrall7bdfa522013-11-15 13:42:56 -0800928static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
Ken Sumralle8744072011-01-18 22:01:55 -0800929 unsigned char *encrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700930 unsigned char *decrypted_master_key,
931 kdf_func kdf, void *kdf_params)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800932{
933 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800934 EVP_CIPHER_CTX d_ctx;
935 int decrypted_len, final_len;
936
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800937 /* Turn the password into a key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700938 kdf(passwd, salt, ikey, kdf_params);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800939
940 /* Initialize the decryption engine */
941 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
942 return -1;
943 }
944 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
945 /* Decrypt the master key */
946 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
947 encrypted_master_key, KEY_LEN_BYTES)) {
948 return -1;
949 }
950 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
951 return -1;
952 }
953
954 if (decrypted_len + final_len != KEY_LEN_BYTES) {
955 return -1;
956 } else {
957 return 0;
958 }
959}
960
Kenny Rootc4c70f12013-06-14 12:11:38 -0700961static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800962{
Kenny Rootc4c70f12013-06-14 12:11:38 -0700963 if (ftr->kdf_type == KDF_SCRYPT) {
964 *kdf = scrypt;
965 *kdf_params = ftr;
966 } else {
967 *kdf = pbkdf2;
968 *kdf_params = NULL;
969 }
970}
971
JP Abgrall7bdfa522013-11-15 13:42:56 -0800972static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700973 struct crypt_mnt_ftr *crypt_ftr)
974{
975 kdf_func kdf;
976 void *kdf_params;
977 int ret;
978
979 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
JP Abgrall7bdfa522013-11-15 13:42:56 -0800980 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, decrypted_master_key, kdf,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700981 kdf_params);
982 if (ret != 0) {
983 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -0700984 }
985
986 return ret;
987}
988
989static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
990 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800991 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -0800992 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800993 EVP_CIPHER_CTX e_ctx;
994 int encrypted_len, final_len;
995
996 /* Get some random bits for a key */
997 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -0800998 read(fd, key_buf, sizeof(key_buf));
999 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001000 close(fd);
1001
1002 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001003 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001004}
1005
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001006static int wait_and_unmount(char *mountpoint)
1007{
1008 int i, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001009#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001010
1011 /* Now umount the tmpfs filesystem */
1012 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
1013 if (umount(mountpoint)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001014 if (errno == EINVAL) {
1015 /* EINVAL is returned if the directory is not a mountpoint,
1016 * i.e. there is no filesystem mounted there. So just get out.
1017 */
1018 break;
1019 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001020 sleep(1);
1021 i++;
1022 } else {
1023 break;
1024 }
1025 }
1026
1027 if (i < WAIT_UNMOUNT_COUNT) {
1028 SLOGD("unmounting %s succeeded\n", mountpoint);
1029 rc = 0;
1030 } else {
1031 SLOGE("unmounting %s failed\n", mountpoint);
1032 rc = -1;
1033 }
1034
1035 return rc;
1036}
1037
Ken Sumrallc5872692013-05-14 15:26:31 -07001038#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001039static int prep_data_fs(void)
1040{
1041 int i;
1042
1043 /* Do the prep of the /data filesystem */
1044 property_set("vold.post_fs_data_done", "0");
1045 property_set("vold.decrypt", "trigger_post_fs_data");
1046 SLOGD("Just triggered post_fs_data\n");
1047
Ken Sumrallc5872692013-05-14 15:26:31 -07001048 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001049 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001050 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001051
1052 property_get("vold.post_fs_data_done", p, "0");
1053 if (*p == '1') {
1054 break;
1055 } else {
1056 usleep(250000);
1057 }
1058 }
1059 if (i == DATA_PREP_TIMEOUT) {
1060 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001061 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001062 return -1;
1063 } else {
1064 SLOGD("post_fs_data done\n");
1065 return 0;
1066 }
1067}
1068
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001069int cryptfs_restart(void)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001070{
1071 char fs_type[32];
1072 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001073 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001074 char fs_options[256];
1075 unsigned long mnt_flags;
1076 struct stat statbuf;
1077 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001078 static int restart_successful = 0;
1079
1080 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001081 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001082 SLOGE("Encrypted filesystem not validated, aborting");
1083 return -1;
1084 }
1085
1086 if (restart_successful) {
1087 SLOGE("System already restarted with encrypted disk, aborting");
1088 return -1;
1089 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001090
1091 /* Here is where we shut down the framework. The init scripts
1092 * start all services in one of three classes: core, main or late_start.
1093 * On boot, we start core and main. Now, we stop main, but not core,
1094 * as core includes vold and a few other really important things that
1095 * we need to keep running. Once main has stopped, we should be able
1096 * to umount the tmpfs /data, then mount the encrypted /data.
1097 * We then restart the class main, and also the class late_start.
1098 * At the moment, I've only put a few things in late_start that I know
1099 * are not needed to bring up the framework, and that also cause problems
1100 * with unmounting the tmpfs /data, but I hope to add add more services
1101 * to the late_start class as we optimize this to decrease the delay
1102 * till the user is asked for the password to the filesystem.
1103 */
1104
1105 /* The init files are setup to stop the class main when vold.decrypt is
1106 * set to trigger_reset_main.
1107 */
1108 property_set("vold.decrypt", "trigger_reset_main");
1109 SLOGD("Just asked init to shut down class main\n");
1110
Ken Sumrall92736ef2012-10-17 20:57:14 -07001111 /* Ugh, shutting down the framework is not synchronous, so until it
1112 * can be fixed, this horrible hack will wait a moment for it all to
1113 * shut down before proceeding. Without it, some devices cannot
1114 * restart the graphics services.
1115 */
1116 sleep(2);
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001117
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001118 /* Now that the framework is shutdown, we should be able to umount()
1119 * the tmpfs filesystem, and mount the real one.
1120 */
1121
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001122 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1123 if (strlen(crypto_blkdev) == 0) {
1124 SLOGE("fs_crypto_blkdev not set\n");
1125 return -1;
1126 }
1127
Ken Sumralle5032c42012-04-01 23:58:44 -07001128 if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
1129 /* If that succeeded, then mount the decrypted filesystem */
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001130 fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001131
Ken Sumralle5032c42012-04-01 23:58:44 -07001132 property_set("vold.decrypt", "trigger_load_persist_props");
1133 /* Create necessary paths on /data */
1134 if (prep_data_fs()) {
1135 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001136 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001137
1138 /* startup service classes main and late_start */
1139 property_set("vold.decrypt", "trigger_restart_framework");
1140 SLOGD("Just triggered restart_framework\n");
1141
1142 /* Give it a few moments to get started */
1143 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001144 }
1145
Ken Sumrall0cc16632011-01-18 20:32:26 -08001146 if (rc == 0) {
1147 restart_successful = 1;
1148 }
1149
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001150 return rc;
1151}
1152
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001153static int do_crypto_complete(char *mount_point)
1154{
1155 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001156 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001157 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001158
1159 property_get("ro.crypto.state", encrypted_state, "");
1160 if (strcmp(encrypted_state, "encrypted") ) {
1161 SLOGE("not running with encryption, aborting");
1162 return 1;
1163 }
1164
Ken Sumrall160b4d62013-04-22 12:15:39 -07001165 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001166 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001167
Ken Sumralle1a45852011-12-14 21:24:27 -08001168 /*
1169 * Only report this error if key_loc is a file and it exists.
1170 * If the device was never encrypted, and /data is not mountable for
1171 * some reason, returning 1 should prevent the UI from presenting the
1172 * a "enter password" screen, or worse, a "press button to wipe the
1173 * device" screen.
1174 */
1175 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1176 SLOGE("master key file does not exist, aborting");
1177 return 1;
1178 } else {
1179 SLOGE("Error getting crypt footer and key\n");
1180 return -1;
1181 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001182 }
1183
1184 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1185 SLOGE("Encryption process didn't finish successfully\n");
1186 return -2; /* -2 is the clue to the UI that there is no usable data on the disk,
1187 * and give the user an option to wipe the disk */
1188 }
1189
1190 /* We passed the test! We shall diminish, and return to the west */
1191 return 0;
1192}
1193
Ken Sumrall29d8da82011-05-18 17:20:07 -07001194static int test_mount_encrypted_fs(char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001195{
1196 struct crypt_mnt_ftr crypt_ftr;
1197 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001198 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001199 char crypto_blkdev[MAXPATHLEN];
1200 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001201 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001202 unsigned int orig_failed_decrypt_count;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001203 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001204 int rc;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001205 kdf_func kdf;
1206 void *kdf_params;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001207
Ken Sumrall0cc16632011-01-18 20:32:26 -08001208 property_get("ro.crypto.state", encrypted_state, "");
Jason parks70a4b3f2011-01-28 10:10:47 -06001209 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001210 SLOGE("encrypted fs already validated or not running with encryption, aborting");
1211 return -1;
1212 }
1213
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001214 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001215
Ken Sumrall160b4d62013-04-22 12:15:39 -07001216 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001217 SLOGE("Error getting crypt footer and key\n");
1218 return -1;
1219 }
Ken Sumralld33d4172011-02-01 00:49:13 -08001220
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001221 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr.fs_size);
1222 orig_failed_decrypt_count = crypt_ftr.failed_decrypt_count;
1223
1224 if (! (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001225 if (decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr)) {
1226 SLOGE("Failed to decrypt master key\n");
1227 return -1;
1228 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001229 }
1230
1231 if (create_crypto_blk_dev(&crypt_ftr, decrypted_master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -07001232 real_blkdev, crypto_blkdev, label)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001233 SLOGE("Error creating decrypted block device\n");
1234 return -1;
1235 }
1236
Alex Klyubin707795a2013-05-10 15:17:07 -07001237 /* If init detects an encrypted filesystem, it writes a file for each such
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001238 * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
1239 * files and passes that data to me */
1240 /* Create a tmp mount point to try mounting the decryptd fs
1241 * Since we're here, the mount_point should be a tmpfs filesystem, so make
1242 * a directory in it to test mount the decrypted filesystem.
1243 */
1244 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1245 mkdir(tmp_mount_point, 0755);
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001246 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001247 SLOGE("Error temp mounting decrypted block device\n");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001248 delete_crypto_blk_dev(label);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001249 crypt_ftr.failed_decrypt_count++;
1250 } else {
1251 /* Success, so just umount and we'll mount it properly when we restart
1252 * the framework.
1253 */
1254 umount(tmp_mount_point);
1255 crypt_ftr.failed_decrypt_count = 0;
1256 }
1257
1258 if (orig_failed_decrypt_count != crypt_ftr.failed_decrypt_count) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001259 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001260 }
1261
1262 if (crypt_ftr.failed_decrypt_count) {
1263 /* We failed to mount the device, so return an error */
1264 rc = crypt_ftr.failed_decrypt_count;
1265
1266 } else {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001267 /* Woot! Success! Save the name of the crypto block device
1268 * so we can mount it when restarting the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001269 */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001270 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001271
1272 /* Also save a the master key so we can reencrypted the key
1273 * the key when we want to change the password on it.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001274 */
Jason parks70a4b3f2011-01-28 10:10:47 -06001275 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001276 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001277 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001278 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001279 rc = 0;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001280 /*
1281 * Upgrade if we're not using the latest KDF.
1282 */
1283 if (crypt_ftr.kdf_type != KDF_SCRYPT) {
1284 crypt_ftr.kdf_type = KDF_SCRYPT;
1285 rc = encrypt_master_key(passwd, crypt_ftr.salt, saved_master_key, crypt_ftr.master_key,
1286 &crypt_ftr);
1287 if (!rc) {
1288 rc = put_crypt_ftr_and_key(&crypt_ftr);
1289 }
1290 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1291 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001292 }
1293
1294 return rc;
1295}
1296
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001297/* Called by vold when it wants to undo the crypto mapping of a volume it
1298 * manages. This is usually in response to a factory reset, when we want
1299 * to undo the crypto mapping so the volume is formatted in the clear.
1300 */
1301int cryptfs_revert_volume(const char *label)
1302{
1303 return delete_crypto_blk_dev((char *)label);
1304}
1305
Ken Sumrall29d8da82011-05-18 17:20:07 -07001306/*
1307 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1308 * Setup a dm-crypt mapping, use the saved master key from
1309 * setting up the /data mapping, and return the new device path.
1310 */
1311int cryptfs_setup_volume(const char *label, int major, int minor,
1312 char *crypto_sys_path, unsigned int max_path,
1313 int *new_major, int *new_minor)
1314{
1315 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1316 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001317 struct stat statbuf;
1318 int nr_sec, fd;
1319
1320 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1321
Ken Sumrall160b4d62013-04-22 12:15:39 -07001322 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001323
1324 /* Update the fs_size field to be the size of the volume */
1325 fd = open(real_blkdev, O_RDONLY);
1326 nr_sec = get_blkdev_size(fd);
1327 close(fd);
1328 if (nr_sec == 0) {
1329 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1330 return -1;
1331 }
1332
1333 sd_crypt_ftr.fs_size = nr_sec;
1334 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1335 crypto_blkdev, label);
1336
1337 stat(crypto_blkdev, &statbuf);
1338 *new_major = MAJOR(statbuf.st_rdev);
1339 *new_minor = MINOR(statbuf.st_rdev);
1340
1341 /* Create path to sys entry for this block device */
1342 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1343
1344 return 0;
1345}
1346
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001347int cryptfs_crypto_complete(void)
1348{
1349 return do_crypto_complete("/data");
1350}
1351
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001352int cryptfs_check_passwd(char *passwd)
1353{
1354 int rc = -1;
1355
Ken Sumrall29d8da82011-05-18 17:20:07 -07001356 rc = test_mount_encrypted_fs(passwd, DATA_MNT_POINT, "userdata");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001357
1358 return rc;
1359}
1360
Ken Sumrall3ad90722011-10-04 20:38:29 -07001361int cryptfs_verify_passwd(char *passwd)
1362{
1363 struct crypt_mnt_ftr crypt_ftr;
1364 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001365 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001366 char encrypted_state[PROPERTY_VALUE_MAX];
1367 int rc;
1368
1369 property_get("ro.crypto.state", encrypted_state, "");
1370 if (strcmp(encrypted_state, "encrypted") ) {
1371 SLOGE("device not encrypted, aborting");
1372 return -2;
1373 }
1374
1375 if (!master_key_saved) {
1376 SLOGE("encrypted fs not yet mounted, aborting");
1377 return -1;
1378 }
1379
1380 if (!saved_mount_point) {
1381 SLOGE("encrypted fs failed to save mount point, aborting");
1382 return -1;
1383 }
1384
Ken Sumrall160b4d62013-04-22 12:15:39 -07001385 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001386 SLOGE("Error getting crypt footer and key\n");
1387 return -1;
1388 }
1389
1390 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1391 /* If the device has no password, then just say the password is valid */
1392 rc = 0;
1393 } else {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001394 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001395 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1396 /* They match, the password is correct */
1397 rc = 0;
1398 } else {
1399 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1400 sleep(1);
1401 rc = 1;
1402 }
1403 }
1404
1405 return rc;
1406}
1407
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001408/* Initialize a crypt_mnt_ftr structure. The keysize is
1409 * defaulted to 16 bytes, and the filesystem size to 0.
1410 * Presumably, at a minimum, the caller will update the
1411 * filesystem size and crypto_type_name after calling this function.
1412 */
1413static void cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
1414{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001415 off64_t off;
1416
1417 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001418 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001419 ftr->major_version = CURRENT_MAJOR_VERSION;
1420 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001421 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001422 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001423
Kenny Rootc4c70f12013-06-14 12:11:38 -07001424 ftr->kdf_type = KDF_SCRYPT;
1425 get_device_scrypt_params(ftr);
1426
Ken Sumrall160b4d62013-04-22 12:15:39 -07001427 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1428 if (get_crypt_ftr_info(NULL, &off) == 0) {
1429 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1430 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1431 ftr->persist_data_size;
1432 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001433}
1434
Ken Sumrall29d8da82011-05-18 17:20:07 -07001435static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001436{
Ken Sumralle550f782013-08-20 13:48:23 -07001437 const char *args[10];
1438 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1439 int num_args;
1440 int status;
1441 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001442 int rc = -1;
1443
Ken Sumrall29d8da82011-05-18 17:20:07 -07001444 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001445 args[0] = "/system/bin/make_ext4fs";
1446 args[1] = "-a";
1447 args[2] = "/data";
1448 args[3] = "-l";
1449 snprintf(size_str, sizeof(size_str), "%lld", size * 512);
1450 args[4] = size_str;
1451 args[5] = crypto_blkdev;
1452 num_args = 6;
1453 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1454 args[0], args[1], args[2], args[3], args[4], args[5]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001455 } else if (type== FAT_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001456 args[0] = "/system/bin/newfs_msdos";
1457 args[1] = "-F";
1458 args[2] = "32";
1459 args[3] = "-O";
1460 args[4] = "android";
1461 args[5] = "-c";
1462 args[6] = "8";
1463 args[7] = "-s";
1464 snprintf(size_str, sizeof(size_str), "%lld", size);
1465 args[8] = size_str;
1466 args[9] = crypto_blkdev;
1467 num_args = 10;
1468 SLOGI("Making empty filesystem with command %s %s %s %s %s %s %s %s %s %s\n",
1469 args[0], args[1], args[2], args[3], args[4], args[5],
1470 args[6], args[7], args[8], args[9]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001471 } else {
1472 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1473 return -1;
1474 }
1475
Ken Sumralle550f782013-08-20 13:48:23 -07001476 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1477
1478 if (tmp != 0) {
1479 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001480 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07001481 if (WIFEXITED(status)) {
1482 if (WEXITSTATUS(status)) {
1483 SLOGE("Error creating filesystem on %s, exit status %d ",
1484 crypto_blkdev, WEXITSTATUS(status));
1485 } else {
1486 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
1487 rc = 0;
1488 }
1489 } else {
1490 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
1491 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001492 }
1493
1494 return rc;
1495}
1496
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001497#define CRYPT_INPLACE_BUFSIZE 4096
1498#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / 512)
Ken Sumrall29d8da82011-05-18 17:20:07 -07001499static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev, off64_t size,
1500 off64_t *size_already_done, off64_t tot_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001501{
1502 int realfd, cryptofd;
1503 char *buf[CRYPT_INPLACE_BUFSIZE];
1504 int rc = -1;
1505 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001506 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001507 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001508
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001509 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
1510 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
1511 return -1;
1512 }
1513
1514 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
1515 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1516 close(realfd);
1517 return -1;
1518 }
1519
1520 /* This is pretty much a simple loop of reading 4K, and writing 4K.
1521 * The size passed in is the number of 512 byte sectors in the filesystem.
1522 * So compute the number of whole 4K blocks we should read/write,
1523 * and the remainder.
1524 */
1525 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
1526 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001527 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
1528 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001529
1530 SLOGE("Encrypting filesystem in place...");
1531
Ken Sumrall29d8da82011-05-18 17:20:07 -07001532 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001533 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001534 /* process the majority of the filesystem in blocks */
1535 for (i=0; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001536 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001537 if (new_pct > cur_pct) {
1538 char buf[8];
1539
1540 cur_pct = new_pct;
1541 snprintf(buf, sizeof(buf), "%lld", cur_pct);
1542 property_set("vold.encrypt_progress", buf);
1543 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001544 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1545 SLOGE("Error reading real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1546 goto errout;
1547 }
1548 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1549 SLOGE("Error writing crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1550 goto errout;
1551 }
1552 }
1553
1554 /* Do any remaining sectors */
1555 for (i=0; i<remainder; i++) {
1556 if (unix_read(realfd, buf, 512) <= 0) {
1557 SLOGE("Error reading rival sectors from real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1558 goto errout;
1559 }
1560 if (unix_write(cryptofd, buf, 512) <= 0) {
1561 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1562 goto errout;
1563 }
1564 }
1565
Ken Sumrall29d8da82011-05-18 17:20:07 -07001566 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001567 rc = 0;
1568
1569errout:
1570 close(realfd);
1571 close(cryptofd);
1572
1573 return rc;
1574}
1575
1576#define CRYPTO_ENABLE_WIPE 1
1577#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001578
1579#define FRAMEWORK_BOOT_WAIT 60
1580
Ken Sumrall29d8da82011-05-18 17:20:07 -07001581static inline int should_encrypt(struct volume_info *volume)
1582{
1583 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
1584 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
1585}
1586
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001587int cryptfs_enable(char *howarg, char *passwd)
1588{
1589 int how = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001590 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN], sd_crypto_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07001591 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001592 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07001593 int rc=-1, fd, i, ret;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001594 struct crypt_mnt_ftr crypt_ftr, sd_crypt_ftr;;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001595 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001596 char tmpfs_options[PROPERTY_VALUE_MAX];
1597 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001598 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07001599 char key_loc[PROPERTY_VALUE_MAX];
1600 char fuse_sdcard[PROPERTY_VALUE_MAX];
1601 char *sd_mnt_point;
1602 char sd_blk_dev[256] = { 0 };
1603 int num_vols;
1604 struct volume_info *vol_list = 0;
1605 off64_t cur_encryption_done=0, tot_encryption_size=0;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001606
1607 property_get("ro.crypto.state", encrypted_state, "");
1608 if (strcmp(encrypted_state, "unencrypted")) {
1609 SLOGE("Device is already running encrypted, aborting");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001610 goto error_unencrypted;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001611 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001612
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001613 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001614
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001615 if (!strcmp(howarg, "wipe")) {
1616 how = CRYPTO_ENABLE_WIPE;
1617 } else if (! strcmp(howarg, "inplace")) {
1618 how = CRYPTO_ENABLE_INPLACE;
1619 } else {
1620 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08001621 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001622 }
1623
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001624 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001625
Ken Sumrall3ed82362011-01-28 23:31:16 -08001626 /* Get the size of the real block device */
1627 fd = open(real_blkdev, O_RDONLY);
1628 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
1629 SLOGE("Cannot get size of block device %s\n", real_blkdev);
1630 goto error_unencrypted;
1631 }
1632 close(fd);
1633
1634 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001635 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001636 unsigned int fs_size_sec, max_fs_size_sec;
1637
1638 fs_size_sec = get_fs_size(real_blkdev);
1639 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1640
1641 if (fs_size_sec > max_fs_size_sec) {
1642 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
1643 goto error_unencrypted;
1644 }
1645 }
1646
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001647 /* Get a wakelock as this may take a while, and we don't want the
1648 * device to sleep on us. We'll grab a partial wakelock, and if the UI
1649 * wants to keep the screen on, it can grab a full wakelock.
1650 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001651 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001652 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
1653
Jeff Sharkey7382f812012-08-23 14:08:59 -07001654 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07001655 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07001656 if (!sd_mnt_point) {
1657 sd_mnt_point = getenv("EXTERNAL_STORAGE");
1658 }
1659 if (!sd_mnt_point) {
1660 sd_mnt_point = "/mnt/sdcard";
1661 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07001662
1663 num_vols=vold_getNumDirectVolumes();
1664 vol_list = malloc(sizeof(struct volume_info) * num_vols);
1665 vold_getDirectVolumeList(vol_list);
1666
1667 for (i=0; i<num_vols; i++) {
1668 if (should_encrypt(&vol_list[i])) {
1669 fd = open(vol_list[i].blk_dev, O_RDONLY);
1670 if ( (vol_list[i].size = get_blkdev_size(fd)) == 0) {
1671 SLOGE("Cannot get size of block device %s\n", vol_list[i].blk_dev);
1672 goto error_unencrypted;
1673 }
1674 close(fd);
1675
Ken Sumrall3b170052011-07-11 15:38:57 -07001676 ret=vold_disableVol(vol_list[i].label);
Ken Sumrall319b1042011-06-14 14:01:55 -07001677 if ((ret < 0) && (ret != UNMOUNT_NOT_MOUNTED_ERR)) {
1678 /* -2 is returned when the device exists but is not currently mounted.
1679 * ignore the error and continue. */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001680 SLOGE("Failed to unmount volume %s\n", vol_list[i].label);
1681 goto error_unencrypted;
1682 }
1683 }
1684 }
1685
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001686 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001687 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001688 */
1689 property_set("vold.decrypt", "trigger_shutdown_framework");
1690 SLOGD("Just asked init to shut down class main\n");
1691
Ken Sumrall425524d2012-06-14 20:55:28 -07001692 if (vold_unmountAllAsecs()) {
1693 /* Just report the error. If any are left mounted,
1694 * umounting /data below will fail and handle the error.
1695 */
1696 SLOGE("Error unmounting internal asecs");
1697 }
1698
Ken Sumrall29d8da82011-05-18 17:20:07 -07001699 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
1700 if (!strcmp(fuse_sdcard, "true")) {
1701 /* This is a device using the fuse layer to emulate the sdcard semantics
1702 * on top of the userdata partition. vold does not manage it, it is managed
1703 * by the sdcard service. The sdcard service was killed by the property trigger
1704 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
1705 * unlike the case for vold managed devices above.
1706 */
1707 if (wait_and_unmount(sd_mnt_point)) {
1708 goto error_shutting_down;
1709 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001710 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001711
1712 /* Now unmount the /data partition. */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001713 if (wait_and_unmount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001714 goto error_shutting_down;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001715 }
1716
1717 /* Do extra work for a better UX when doing the long inplace encryption */
1718 if (how == CRYPTO_ENABLE_INPLACE) {
1719 /* Now that /data is unmounted, we need to mount a tmpfs
1720 * /data, set a property saying we're doing inplace encryption,
1721 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001722 */
Ken Sumralle5032c42012-04-01 23:58:44 -07001723 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001724 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001725 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001726 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08001727 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001728
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001729 /* restart the framework. */
1730 /* Create necessary paths on /data */
1731 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001732 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001733 }
1734
Ken Sumrall92736ef2012-10-17 20:57:14 -07001735 /* Ugh, shutting down the framework is not synchronous, so until it
1736 * can be fixed, this horrible hack will wait a moment for it all to
1737 * shut down before proceeding. Without it, some devices cannot
1738 * restart the graphics services.
1739 */
1740 sleep(2);
1741
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001742 /* startup service classes main and late_start */
1743 property_set("vold.decrypt", "trigger_restart_min_framework");
1744 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001745
Ken Sumrall7df84122011-01-18 14:04:08 -08001746 /* OK, the framework is restarted and will soon be showing a
1747 * progress bar. Time to setup an encrypted mapping, and
1748 * either write a new filesystem, or encrypt in place updating
1749 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001750 */
1751 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001752
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001753 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001754 /* Initialize a crypt_mnt_ftr for the partition */
1755 cryptfs_init_crypt_mnt_ftr(&crypt_ftr);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001756
Ken Sumrall29d8da82011-05-18 17:20:07 -07001757 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
1758 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1759 } else {
1760 crypt_ftr.fs_size = nr_sec;
1761 }
Ken Sumralld33d4172011-02-01 00:49:13 -08001762 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001763 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
1764
1765 /* Make an encrypted master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001766 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001767 SLOGE("Cannot create encrypted master key\n");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001768 goto error_unencrypted;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001769 }
1770
1771 /* Write the key to the end of the partition */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001772 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001773
Ken Sumrall160b4d62013-04-22 12:15:39 -07001774 /* If any persistent data has been remembered, save it.
1775 * If none, create a valid empty table and save that.
1776 */
1777 if (!persist_data) {
1778 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
1779 if (pdata) {
1780 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
1781 persist_data = pdata;
1782 }
1783 }
1784 if (persist_data) {
1785 save_persistent_data();
1786 }
1787
JP Abgrall7bdfa522013-11-15 13:42:56 -08001788 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001789 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
1790 "userdata");
1791
Ken Sumrall128626f2011-06-28 18:45:14 -07001792 /* The size of the userdata partition, and add in the vold volumes below */
1793 tot_encryption_size = crypt_ftr.fs_size;
1794
Ken Sumrall29d8da82011-05-18 17:20:07 -07001795 /* setup crypto mapping for all encryptable volumes handled by vold */
1796 for (i=0; i<num_vols; i++) {
1797 if (should_encrypt(&vol_list[i])) {
1798 vol_list[i].crypt_ftr = crypt_ftr; /* gotta love struct assign */
1799 vol_list[i].crypt_ftr.fs_size = vol_list[i].size;
1800 create_crypto_blk_dev(&vol_list[i].crypt_ftr, decrypted_master_key,
1801 vol_list[i].blk_dev, vol_list[i].crypto_blkdev,
1802 vol_list[i].label);
Ken Sumrall128626f2011-06-28 18:45:14 -07001803 tot_encryption_size += vol_list[i].size;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001804 }
1805 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001806
1807 if (how == CRYPTO_ENABLE_WIPE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001808 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr.fs_size, EXT4_FS);
1809 /* Encrypt all encryptable volumes handled by vold */
1810 if (!rc) {
1811 for (i=0; i<num_vols; i++) {
1812 if (should_encrypt(&vol_list[i])) {
1813 rc = cryptfs_enable_wipe(vol_list[i].crypto_blkdev,
1814 vol_list[i].crypt_ftr.fs_size, FAT_FS);
1815 }
1816 }
1817 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001818 } else if (how == CRYPTO_ENABLE_INPLACE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001819 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr.fs_size,
1820 &cur_encryption_done, tot_encryption_size);
1821 /* Encrypt all encryptable volumes handled by vold */
1822 if (!rc) {
1823 for (i=0; i<num_vols; i++) {
1824 if (should_encrypt(&vol_list[i])) {
1825 rc = cryptfs_enable_inplace(vol_list[i].crypto_blkdev,
1826 vol_list[i].blk_dev,
1827 vol_list[i].crypt_ftr.fs_size,
1828 &cur_encryption_done, tot_encryption_size);
1829 }
1830 }
1831 }
1832 if (!rc) {
1833 /* The inplace routine never actually sets the progress to 100%
1834 * due to the round down nature of integer division, so set it here */
1835 property_set("vold.encrypt_progress", "100");
1836 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001837 } else {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001838 /* Shouldn't happen */
1839 SLOGE("cryptfs_enable: internal error, unknown option\n");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001840 goto error_unencrypted;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001841 }
1842
1843 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001844 delete_crypto_blk_dev("userdata");
1845 for (i=0; i<num_vols; i++) {
1846 if (should_encrypt(&vol_list[i])) {
1847 delete_crypto_blk_dev(vol_list[i].label);
1848 }
1849 }
1850
1851 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001852
1853 if (! rc) {
1854 /* Success */
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001855
Ken Sumralld33d4172011-02-01 00:49:13 -08001856 /* Clear the encryption in progres flag in the footer */
1857 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001858 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08001859
Ken Sumrall29d8da82011-05-18 17:20:07 -07001860 sleep(2); /* Give the UI a chance to show 100% progress */
Ken Sumralladfba362013-06-04 16:37:52 -07001861 cryptfs_reboot(0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001862 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001863 char value[PROPERTY_VALUE_MAX];
1864
Ken Sumrall319369a2012-06-27 16:30:18 -07001865 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001866 if (!strcmp(value, "1")) {
1867 /* wipe data if encryption failed */
1868 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
1869 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07001870 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001871 if (fd >= 0) {
1872 write(fd, "--wipe_data", strlen("--wipe_data") + 1);
1873 close(fd);
1874 } else {
1875 SLOGE("could not open /cache/recovery/command\n");
1876 }
Ken Sumralladfba362013-06-04 16:37:52 -07001877 cryptfs_reboot(1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001878 } else {
1879 /* set property to trigger dialog */
1880 property_set("vold.encrypt_progress", "error_partially_encrypted");
1881 release_wake_lock(lockid);
1882 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001883 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001884 }
1885
Ken Sumrall3ed82362011-01-28 23:31:16 -08001886 /* hrm, the encrypt step claims success, but the reboot failed.
1887 * This should not happen.
1888 * Set the property and return. Hope the framework can deal with it.
1889 */
1890 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001891 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001892 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08001893
1894error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07001895 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001896 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001897 if (lockid[0]) {
1898 release_wake_lock(lockid);
1899 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001900 return -1;
1901
1902error_shutting_down:
1903 /* we failed, and have not encrypted anthing, so the users's data is still intact,
1904 * but the framework is stopped and not restarted to show the error, so it's up to
1905 * vold to restart the system.
1906 */
1907 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Ken Sumralladfba362013-06-04 16:37:52 -07001908 cryptfs_reboot(0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001909
1910 /* shouldn't get here */
1911 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001912 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001913 if (lockid[0]) {
1914 release_wake_lock(lockid);
1915 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001916 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001917}
1918
Jason parks70a4b3f2011-01-28 10:10:47 -06001919int cryptfs_changepw(char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001920{
1921 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001922 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001923
1924 /* This is only allowed after we've successfully decrypted the master key */
Jason parks70a4b3f2011-01-28 10:10:47 -06001925 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001926 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001927 return -1;
1928 }
1929
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001930 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001931 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall57b63e62011-01-17 18:29:19 -08001932 SLOGE("Error getting crypt footer and key");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001933 return -1;
1934 }
1935
Kenny Rootc4c70f12013-06-14 12:11:38 -07001936 encrypt_master_key(newpw, crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001937
Jason parks70a4b3f2011-01-28 10:10:47 -06001938 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001939 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001940
1941 return 0;
1942}
Ken Sumrall160b4d62013-04-22 12:15:39 -07001943
1944static int persist_get_key(char *fieldname, char *value)
1945{
1946 unsigned int i;
1947
1948 if (persist_data == NULL) {
1949 return -1;
1950 }
1951 for (i = 0; i < persist_data->persist_valid_entries; i++) {
1952 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
1953 /* We found it! */
1954 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
1955 return 0;
1956 }
1957 }
1958
1959 return -1;
1960}
1961
1962static int persist_set_key(char *fieldname, char *value, int encrypted)
1963{
1964 unsigned int i;
1965 unsigned int num;
1966 struct crypt_mnt_ftr crypt_ftr;
1967 unsigned int max_persistent_entries;
1968 unsigned int dsize;
1969
1970 if (persist_data == NULL) {
1971 return -1;
1972 }
1973
1974 /* If encrypted, use the values from the crypt_ftr, otherwise
1975 * use the values for the current spec.
1976 */
1977 if (encrypted) {
1978 if(get_crypt_ftr_and_key(&crypt_ftr)) {
1979 return -1;
1980 }
1981 dsize = crypt_ftr.persist_data_size;
1982 } else {
1983 dsize = CRYPT_PERSIST_DATA_SIZE;
1984 }
1985 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
1986 sizeof(struct crypt_persist_entry);
1987
1988 num = persist_data->persist_valid_entries;
1989
1990 for (i = 0; i < num; i++) {
1991 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
1992 /* We found an existing entry, update it! */
1993 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
1994 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
1995 return 0;
1996 }
1997 }
1998
1999 /* We didn't find it, add it to the end, if there is room */
2000 if (persist_data->persist_valid_entries < max_persistent_entries) {
2001 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2002 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2003 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2004 persist_data->persist_valid_entries++;
2005 return 0;
2006 }
2007
2008 return -1;
2009}
2010
2011/* Return the value of the specified field. */
2012int cryptfs_getfield(char *fieldname, char *value, int len)
2013{
2014 char temp_value[PROPERTY_VALUE_MAX];
2015 char real_blkdev[MAXPATHLEN];
2016 /* 0 is success, 1 is not encrypted,
2017 * -1 is value not set, -2 is any other error
2018 */
2019 int rc = -2;
2020
2021 if (persist_data == NULL) {
2022 load_persistent_data();
2023 if (persist_data == NULL) {
2024 SLOGE("Getfield error, cannot load persistent data");
2025 goto out;
2026 }
2027 }
2028
2029 if (!persist_get_key(fieldname, temp_value)) {
2030 /* We found it, copy it to the caller's buffer and return */
2031 strlcpy(value, temp_value, len);
2032 rc = 0;
2033 } else {
2034 /* Sadness, it's not there. Return the error */
2035 rc = -1;
2036 }
2037
2038out:
2039 return rc;
2040}
2041
2042/* Set the value of the specified field. */
2043int cryptfs_setfield(char *fieldname, char *value)
2044{
2045 struct crypt_persist_data stored_pdata;
2046 struct crypt_persist_data *pdata_p;
2047 struct crypt_mnt_ftr crypt_ftr;
2048 char encrypted_state[PROPERTY_VALUE_MAX];
2049 /* 0 is success, -1 is an error */
2050 int rc = -1;
2051 int encrypted = 0;
2052
2053 if (persist_data == NULL) {
2054 load_persistent_data();
2055 if (persist_data == NULL) {
2056 SLOGE("Setfield error, cannot load persistent data");
2057 goto out;
2058 }
2059 }
2060
2061 property_get("ro.crypto.state", encrypted_state, "");
2062 if (!strcmp(encrypted_state, "encrypted") ) {
2063 encrypted = 1;
2064 }
2065
2066 if (persist_set_key(fieldname, value, encrypted)) {
2067 goto out;
2068 }
2069
2070 /* If we are running encrypted, save the persistent data now */
2071 if (encrypted) {
2072 if (save_persistent_data()) {
2073 SLOGE("Setfield error, cannot save persistent data");
2074 goto out;
2075 }
2076 }
2077
2078 rc = 0;
2079
2080out:
2081 return rc;
2082}