blob: 40ad36a7d107b16ec835d943622ae96fdba76bb5 [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
23#include <sys/types.h>
Ken Sumralle550f782013-08-20 13:48:23 -070024#include <sys/wait.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080025#include <sys/stat.h>
26#include <fcntl.h>
27#include <unistd.h>
28#include <stdio.h>
29#include <sys/ioctl.h>
30#include <linux/dm-ioctl.h>
31#include <libgen.h>
32#include <stdlib.h>
33#include <sys/param.h>
34#include <string.h>
35#include <sys/mount.h>
36#include <openssl/evp.h>
Ken Sumrall8ddbe402011-01-17 15:26:29 -080037#include <openssl/sha.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080038#include <errno.h>
Ken Sumrall3ed82362011-01-28 23:31:16 -080039#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070040#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070041#include <fs_mgr.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080042#include "cryptfs.h"
43#define LOG_TAG "Cryptfs"
44#include "cutils/log.h"
45#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070046#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080047#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070048#include <logwrap/logwrap.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070049#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070050#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070051#include "crypto_scrypt.h"
Paul Lawrenceae59fe62014-01-21 08:23:27 -080052#include "ext4_utils.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080053
Mark Salyzyn3e971272014-01-21 13:27:04 -080054#define UNUSED __attribute__((unused))
55
Ken Sumrall8f869aa2010-12-03 03:47:09 -080056#define DM_CRYPT_BUF_SIZE 4096
57
Jason parks70a4b3f2011-01-28 10:10:47 -060058#define HASH_COUNT 2000
59#define KEY_LEN_BYTES 16
60#define IV_LEN_BYTES 16
61
Ken Sumrall29d8da82011-05-18 17:20:07 -070062#define KEY_IN_FOOTER "footer"
63
64#define EXT4_FS 1
65#define FAT_FS 2
66
Ken Sumralle919efe2012-09-29 17:07:41 -070067#define TABLE_LOAD_RETRIES 10
68
Ken Sumrall8f869aa2010-12-03 03:47:09 -080069char *me = "cryptfs";
70
Jason parks70a4b3f2011-01-28 10:10:47 -060071static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070072static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060073static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -070074static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -080075
76extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -080077
Ken Sumralladfba362013-06-04 16:37:52 -070078static void cryptfs_reboot(int recovery)
79{
80 if (recovery) {
81 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
82 } else {
83 property_set(ANDROID_RB_PROPERTY, "reboot");
84 }
85 sleep(20);
86
87 /* Shouldn't get here, reboot should happen before sleep times out */
88 return;
89}
90
Ken Sumrall8f869aa2010-12-03 03:47:09 -080091static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
92{
93 memset(io, 0, dataSize);
94 io->data_size = dataSize;
95 io->data_start = sizeof(struct dm_ioctl);
96 io->version[0] = 4;
97 io->version[1] = 0;
98 io->version[2] = 0;
99 io->flags = flags;
100 if (name) {
101 strncpy(io->name, name, sizeof(io->name));
102 }
103}
104
Kenny Rootc4c70f12013-06-14 12:11:38 -0700105/**
106 * Gets the default device scrypt parameters for key derivation time tuning.
107 * The parameters should lead to about one second derivation time for the
108 * given device.
109 */
110static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
111 const int default_params[] = SCRYPT_DEFAULTS;
112 int params[] = SCRYPT_DEFAULTS;
113 char paramstr[PROPERTY_VALUE_MAX];
114 char *token;
115 char *saveptr;
116 int i;
117
118 property_get(SCRYPT_PROP, paramstr, "");
119 if (paramstr[0] != '\0') {
120 /*
121 * The token we're looking for should be three integers separated by
122 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
123 */
Kenny Root2947e342013-08-14 15:54:49 -0700124 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
125 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700126 i++, token = strtok_r(NULL, ":", &saveptr)) {
127 char *endptr;
128 params[i] = strtol(token, &endptr, 10);
129
130 /*
131 * Check that there was a valid number and it's 8-bit. If not,
132 * break out and the end check will take the default values.
133 */
134 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
135 break;
136 }
137 }
138
139 /*
140 * If there were not enough tokens or a token was malformed (not an
141 * integer), it will end up here and the default parameters can be
142 * taken.
143 */
144 if ((i != 3) || (token != NULL)) {
145 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
146 memcpy(params, default_params, sizeof(params));
147 }
148 }
149
150 ftr->N_factor = params[0];
151 ftr->r_factor = params[1];
152 ftr->p_factor = params[2];
153}
154
Ken Sumrall3ed82362011-01-28 23:31:16 -0800155static unsigned int get_fs_size(char *dev)
156{
157 int fd, block_size;
158 struct ext4_super_block sb;
159 off64_t len;
160
161 if ((fd = open(dev, O_RDONLY)) < 0) {
162 SLOGE("Cannot open device to get filesystem size ");
163 return 0;
164 }
165
166 if (lseek64(fd, 1024, SEEK_SET) < 0) {
167 SLOGE("Cannot seek to superblock");
168 return 0;
169 }
170
171 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
172 SLOGE("Cannot read superblock");
173 return 0;
174 }
175
176 close(fd);
177
178 block_size = 1024 << sb.s_log_block_size;
179 /* compute length in bytes */
180 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
181
182 /* return length in sectors */
183 return (unsigned int) (len / 512);
184}
185
Ken Sumrall160b4d62013-04-22 12:15:39 -0700186static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
187{
188 static int cached_data = 0;
189 static off64_t cached_off = 0;
190 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
191 int fd;
192 char key_loc[PROPERTY_VALUE_MAX];
193 char real_blkdev[PROPERTY_VALUE_MAX];
194 unsigned int nr_sec;
195 int rc = -1;
196
197 if (!cached_data) {
198 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
199
200 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
201 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
202 SLOGE("Cannot open real block device %s\n", real_blkdev);
203 return -1;
204 }
205
206 if ((nr_sec = get_blkdev_size(fd))) {
207 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
208 * encryption info footer and key, and plenty of bytes to spare for future
209 * growth.
210 */
211 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
212 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
213 cached_data = 1;
214 } else {
215 SLOGE("Cannot get size of block device %s\n", real_blkdev);
216 }
217 close(fd);
218 } else {
219 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
220 cached_off = 0;
221 cached_data = 1;
222 }
223 }
224
225 if (cached_data) {
226 if (metadata_fname) {
227 *metadata_fname = cached_metadata_fname;
228 }
229 if (off) {
230 *off = cached_off;
231 }
232 rc = 0;
233 }
234
235 return rc;
236}
237
Ken Sumralle8744072011-01-18 22:01:55 -0800238/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800239 * update the failed mount count but not change the key.
240 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700241static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800242{
243 int fd;
244 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700245 /* starting_off is set to the SEEK_SET offset
246 * where the crypto structure starts
247 */
248 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800249 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700250 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700251 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800252
Ken Sumrall160b4d62013-04-22 12:15:39 -0700253 if (get_crypt_ftr_info(&fname, &starting_off)) {
254 SLOGE("Unable to get crypt_ftr_info\n");
255 return -1;
256 }
257 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700258 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700259 return -1;
260 }
Ken Sumralle550f782013-08-20 13:48:23 -0700261 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
262 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700263 return -1;
264 }
265
266 /* Seek to the start of the crypt footer */
267 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
268 SLOGE("Cannot seek to real block device footer\n");
269 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800270 }
271
272 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
273 SLOGE("Cannot write real block device footer\n");
274 goto errout;
275 }
276
Ken Sumrall3be890f2011-09-14 16:53:46 -0700277 fstat(fd, &statbuf);
278 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700279 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700280 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800281 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800282 goto errout;
283 }
284 }
285
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800286 /* Success! */
287 rc = 0;
288
289errout:
290 close(fd);
291 return rc;
292
293}
294
Ken Sumrall160b4d62013-04-22 12:15:39 -0700295static inline int unix_read(int fd, void* buff, int len)
296{
297 return TEMP_FAILURE_RETRY(read(fd, buff, len));
298}
299
300static inline int unix_write(int fd, const void* buff, int len)
301{
302 return TEMP_FAILURE_RETRY(write(fd, buff, len));
303}
304
305static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
306{
307 memset(pdata, 0, len);
308 pdata->persist_magic = PERSIST_DATA_MAGIC;
309 pdata->persist_valid_entries = 0;
310}
311
312/* A routine to update the passed in crypt_ftr to the lastest version.
313 * fd is open read/write on the device that holds the crypto footer and persistent
314 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
315 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
316 */
317static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
318{
Kenny Root7434b312013-06-14 11:29:53 -0700319 int orig_major = crypt_ftr->major_version;
320 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700321
Kenny Root7434b312013-06-14 11:29:53 -0700322 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
323 struct crypt_persist_data *pdata;
324 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700325
Kenny Rootc4c70f12013-06-14 12:11:38 -0700326 SLOGW("upgrading crypto footer to 1.1");
327
Kenny Root7434b312013-06-14 11:29:53 -0700328 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
329 if (pdata == NULL) {
330 SLOGE("Cannot allocate persisent data\n");
331 return;
332 }
333 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
334
335 /* Need to initialize the persistent data area */
336 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
337 SLOGE("Cannot seek to persisent data offset\n");
338 return;
339 }
340 /* Write all zeros to the first copy, making it invalid */
341 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
342
343 /* Write a valid but empty structure to the second copy */
344 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
345 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
346
347 /* Update the footer */
348 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
349 crypt_ftr->persist_data_offset[0] = pdata_offset;
350 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
351 crypt_ftr->minor_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700352 }
353
Kenny Rootc4c70f12013-06-14 12:11:38 -0700354 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version)) {
355 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800356 /* But keep the old kdf_type.
357 * It will get updated later to KDF_SCRYPT after the password has been verified.
358 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700359 crypt_ftr->kdf_type = KDF_PBKDF2;
360 get_device_scrypt_params(crypt_ftr);
361 crypt_ftr->minor_version = 2;
362 }
363
Kenny Root7434b312013-06-14 11:29:53 -0700364 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
365 if (lseek64(fd, offset, SEEK_SET) == -1) {
366 SLOGE("Cannot seek to crypt footer\n");
367 return;
368 }
369 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700370 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700371}
372
373
374static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800375{
376 int fd;
377 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700378 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800379 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700380 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700381 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800382
Ken Sumrall160b4d62013-04-22 12:15:39 -0700383 if (get_crypt_ftr_info(&fname, &starting_off)) {
384 SLOGE("Unable to get crypt_ftr_info\n");
385 return -1;
386 }
387 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700388 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700389 return -1;
390 }
391 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700392 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700393 return -1;
394 }
395
396 /* Make sure it's 16 Kbytes in length */
397 fstat(fd, &statbuf);
398 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
399 SLOGE("footer file %s is not the expected size!\n", fname);
400 goto errout;
401 }
402
403 /* Seek to the start of the crypt footer */
404 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
405 SLOGE("Cannot seek to real block device footer\n");
406 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800407 }
408
409 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
410 SLOGE("Cannot read real block device footer\n");
411 goto errout;
412 }
413
414 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700415 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800416 goto errout;
417 }
418
Kenny Rootc96a5f82013-06-14 12:08:28 -0700419 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
420 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
421 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800422 goto errout;
423 }
424
Kenny Rootc96a5f82013-06-14 12:08:28 -0700425 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
426 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
427 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800428 }
429
Ken Sumrall160b4d62013-04-22 12:15:39 -0700430 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
431 * copy on disk before returning.
432 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700433 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700434 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800435 }
436
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800437 /* Success! */
438 rc = 0;
439
440errout:
441 close(fd);
442 return rc;
443}
444
Ken Sumrall160b4d62013-04-22 12:15:39 -0700445static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
446{
447 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
448 crypt_ftr->persist_data_offset[1]) {
449 SLOGE("Crypt_ftr persist data regions overlap");
450 return -1;
451 }
452
453 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
454 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
455 return -1;
456 }
457
458 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
459 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
460 CRYPT_FOOTER_OFFSET) {
461 SLOGE("Persistent data extends past crypto footer");
462 return -1;
463 }
464
465 return 0;
466}
467
468static int load_persistent_data(void)
469{
470 struct crypt_mnt_ftr crypt_ftr;
471 struct crypt_persist_data *pdata = NULL;
472 char encrypted_state[PROPERTY_VALUE_MAX];
473 char *fname;
474 int found = 0;
475 int fd;
476 int ret;
477 int i;
478
479 if (persist_data) {
480 /* Nothing to do, we've already loaded or initialized it */
481 return 0;
482 }
483
484
485 /* If not encrypted, just allocate an empty table and initialize it */
486 property_get("ro.crypto.state", encrypted_state, "");
487 if (strcmp(encrypted_state, "encrypted") ) {
488 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
489 if (pdata) {
490 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
491 persist_data = pdata;
492 return 0;
493 }
494 return -1;
495 }
496
497 if(get_crypt_ftr_and_key(&crypt_ftr)) {
498 return -1;
499 }
500
501 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
502 SLOGE("Crypt_ftr version doesn't support persistent data");
503 return -1;
504 }
505
506 if (get_crypt_ftr_info(&fname, NULL)) {
507 return -1;
508 }
509
510 ret = validate_persistent_data_storage(&crypt_ftr);
511 if (ret) {
512 return -1;
513 }
514
515 fd = open(fname, O_RDONLY);
516 if (fd < 0) {
517 SLOGE("Cannot open %s metadata file", fname);
518 return -1;
519 }
520
521 if (persist_data == NULL) {
522 pdata = malloc(crypt_ftr.persist_data_size);
523 if (pdata == NULL) {
524 SLOGE("Cannot allocate memory for persistent data");
525 goto err;
526 }
527 }
528
529 for (i = 0; i < 2; i++) {
530 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
531 SLOGE("Cannot seek to read persistent data on %s", fname);
532 goto err2;
533 }
534 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
535 SLOGE("Error reading persistent data on iteration %d", i);
536 goto err2;
537 }
538 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
539 found = 1;
540 break;
541 }
542 }
543
544 if (!found) {
545 SLOGI("Could not find valid persistent data, creating");
546 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
547 }
548
549 /* Success */
550 persist_data = pdata;
551 close(fd);
552 return 0;
553
554err2:
555 free(pdata);
556
557err:
558 close(fd);
559 return -1;
560}
561
562static int save_persistent_data(void)
563{
564 struct crypt_mnt_ftr crypt_ftr;
565 struct crypt_persist_data *pdata;
566 char *fname;
567 off64_t write_offset;
568 off64_t erase_offset;
569 int found = 0;
570 int fd;
571 int ret;
572
573 if (persist_data == NULL) {
574 SLOGE("No persistent data to save");
575 return -1;
576 }
577
578 if(get_crypt_ftr_and_key(&crypt_ftr)) {
579 return -1;
580 }
581
582 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
583 SLOGE("Crypt_ftr version doesn't support persistent data");
584 return -1;
585 }
586
587 ret = validate_persistent_data_storage(&crypt_ftr);
588 if (ret) {
589 return -1;
590 }
591
592 if (get_crypt_ftr_info(&fname, NULL)) {
593 return -1;
594 }
595
596 fd = open(fname, O_RDWR);
597 if (fd < 0) {
598 SLOGE("Cannot open %s metadata file", fname);
599 return -1;
600 }
601
602 pdata = malloc(crypt_ftr.persist_data_size);
603 if (pdata == NULL) {
604 SLOGE("Cannot allocate persistant data");
605 goto err;
606 }
607
608 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
609 SLOGE("Cannot seek to read persistent data on %s", fname);
610 goto err2;
611 }
612
613 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
614 SLOGE("Error reading persistent data before save");
615 goto err2;
616 }
617
618 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
619 /* The first copy is the curent valid copy, so write to
620 * the second copy and erase this one */
621 write_offset = crypt_ftr.persist_data_offset[1];
622 erase_offset = crypt_ftr.persist_data_offset[0];
623 } else {
624 /* The second copy must be the valid copy, so write to
625 * the first copy, and erase the second */
626 write_offset = crypt_ftr.persist_data_offset[0];
627 erase_offset = crypt_ftr.persist_data_offset[1];
628 }
629
630 /* Write the new copy first, if successful, then erase the old copy */
631 if (lseek(fd, write_offset, SEEK_SET) < 0) {
632 SLOGE("Cannot seek to write persistent data");
633 goto err2;
634 }
635 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
636 (int) crypt_ftr.persist_data_size) {
637 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
638 SLOGE("Cannot seek to erase previous persistent data");
639 goto err2;
640 }
641 fsync(fd);
642 memset(pdata, 0, crypt_ftr.persist_data_size);
643 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
644 (int) crypt_ftr.persist_data_size) {
645 SLOGE("Cannot write to erase previous persistent data");
646 goto err2;
647 }
648 fsync(fd);
649 } else {
650 SLOGE("Cannot write to save persistent data");
651 goto err2;
652 }
653
654 /* Success */
655 free(pdata);
656 close(fd);
657 return 0;
658
659err2:
660 free(pdata);
661err:
662 close(fd);
663 return -1;
664}
665
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800666/* Convert a binary key of specified length into an ascii hex string equivalent,
667 * without the leading 0x and with null termination
668 */
669void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
670 char *master_key_ascii)
671{
672 unsigned int i, a;
673 unsigned char nibble;
674
675 for (i=0, a=0; i<keysize; i++, a+=2) {
676 /* For each byte, write out two ascii hex digits */
677 nibble = (master_key[i] >> 4) & 0xf;
678 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
679
680 nibble = master_key[i] & 0xf;
681 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
682 }
683
684 /* Add the null termination */
685 master_key_ascii[a] = '\0';
686
687}
688
Ken Sumralldb5e0262013-02-05 17:39:48 -0800689static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
690 char *real_blk_name, const char *name, int fd,
691 char *extra_params)
692{
693 char buffer[DM_CRYPT_BUF_SIZE];
694 struct dm_ioctl *io;
695 struct dm_target_spec *tgt;
696 char *crypt_params;
697 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
698 int i;
699
700 io = (struct dm_ioctl *) buffer;
701
702 /* Load the mapping table for this device */
703 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
704
705 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
706 io->target_count = 1;
707 tgt->status = 0;
708 tgt->sector_start = 0;
709 tgt->length = crypt_ftr->fs_size;
710 strcpy(tgt->target_type, "crypt");
711
712 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
713 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
714 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
715 master_key_ascii, real_blk_name, extra_params);
716 crypt_params += strlen(crypt_params) + 1;
717 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
718 tgt->next = crypt_params - buffer;
719
720 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
721 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
722 break;
723 }
724 usleep(500000);
725 }
726
727 if (i == TABLE_LOAD_RETRIES) {
728 /* We failed to load the table, return an error */
729 return -1;
730 } else {
731 return i + 1;
732 }
733}
734
735
736static int get_dm_crypt_version(int fd, const char *name, int *version)
737{
738 char buffer[DM_CRYPT_BUF_SIZE];
739 struct dm_ioctl *io;
740 struct dm_target_versions *v;
741 int i;
742
743 io = (struct dm_ioctl *) buffer;
744
745 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
746
747 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
748 return -1;
749 }
750
751 /* Iterate over the returned versions, looking for name of "crypt".
752 * When found, get and return the version.
753 */
754 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
755 while (v->next) {
756 if (! strcmp(v->name, "crypt")) {
757 /* We found the crypt driver, return the version, and get out */
758 version[0] = v->version[0];
759 version[1] = v->version[1];
760 version[2] = v->version[2];
761 return 0;
762 }
763 v = (struct dm_target_versions *)(((char *)v) + v->next);
764 }
765
766 return -1;
767}
768
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800769static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -0700770 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800771{
772 char buffer[DM_CRYPT_BUF_SIZE];
773 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
774 char *crypt_params;
775 struct dm_ioctl *io;
776 struct dm_target_spec *tgt;
777 unsigned int minor;
778 int fd;
Ken Sumralle919efe2012-09-29 17:07:41 -0700779 int i;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800780 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800781 int version[3];
782 char *extra_params;
783 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800784
785 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
786 SLOGE("Cannot open device-mapper\n");
787 goto errout;
788 }
789
790 io = (struct dm_ioctl *) buffer;
791
792 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
793 if (ioctl(fd, DM_DEV_CREATE, io)) {
794 SLOGE("Cannot create dm-crypt device\n");
795 goto errout;
796 }
797
798 /* Get the device status, in particular, the name of it's device file */
799 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
800 if (ioctl(fd, DM_DEV_STATUS, io)) {
801 SLOGE("Cannot retrieve dm-crypt device status\n");
802 goto errout;
803 }
804 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
805 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
806
Ken Sumralldb5e0262013-02-05 17:39:48 -0800807 extra_params = "";
808 if (! get_dm_crypt_version(fd, name, version)) {
809 /* Support for allow_discards was added in version 1.11.0 */
810 if ((version[0] >= 2) ||
811 ((version[0] == 1) && (version[1] >= 11))) {
812 extra_params = "1 allow_discards";
813 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
814 }
Ken Sumralle919efe2012-09-29 17:07:41 -0700815 }
816
Ken Sumralldb5e0262013-02-05 17:39:48 -0800817 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
818 fd, extra_params);
819 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800820 SLOGE("Cannot load dm-crypt mapping table.\n");
821 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800822 } else if (load_count > 1) {
823 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800824 }
825
826 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -0800827 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800828
829 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
830 SLOGE("Cannot resume the dm-crypt device\n");
831 goto errout;
832 }
833
834 /* We made it here with no errors. Woot! */
835 retval = 0;
836
837errout:
838 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
839
840 return retval;
841}
842
Ken Sumrall29d8da82011-05-18 17:20:07 -0700843static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800844{
845 int fd;
846 char buffer[DM_CRYPT_BUF_SIZE];
847 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800848 int retval = -1;
849
850 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
851 SLOGE("Cannot open device-mapper\n");
852 goto errout;
853 }
854
855 io = (struct dm_ioctl *) buffer;
856
857 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
858 if (ioctl(fd, DM_DEV_REMOVE, io)) {
859 SLOGE("Cannot remove dm-crypt device\n");
860 goto errout;
861 }
862
863 /* We made it here with no errors. Woot! */
864 retval = 0;
865
866errout:
867 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
868
869 return retval;
870
871}
872
Mark Salyzyn3e971272014-01-21 13:27:04 -0800873static void pbkdf2(char *passwd, unsigned char *salt, unsigned char *ikey, void *params UNUSED) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800874 /* Turn the password into a key and IV that can decrypt the master key */
Ken Sumralle8744072011-01-18 22:01:55 -0800875 PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800876 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800877}
878
Kenny Rootc4c70f12013-06-14 12:11:38 -0700879static void scrypt(char *passwd, unsigned char *salt, unsigned char *ikey, void *params) {
880 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
881
882 int N = 1 << ftr->N_factor;
883 int r = 1 << ftr->r_factor;
884 int p = 1 << ftr->p_factor;
885
886 /* Turn the password into a key and IV that can decrypt the master key */
887 crypto_scrypt((unsigned char *) passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
888 KEY_LEN_BYTES + IV_LEN_BYTES);
889}
890
Ken Sumralle8744072011-01-18 22:01:55 -0800891static int encrypt_master_key(char *passwd, unsigned char *salt,
892 unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700893 unsigned char *encrypted_master_key,
894 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800895{
896 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
897 EVP_CIPHER_CTX e_ctx;
898 int encrypted_len, final_len;
899
900 /* Turn the password into a key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700901 get_device_scrypt_params(crypt_ftr);
902 scrypt(passwd, salt, ikey, crypt_ftr);
903
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800904 /* Initialize the decryption engine */
905 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
906 SLOGE("EVP_EncryptInit failed\n");
907 return -1;
908 }
909 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800910
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800911 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800912 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
913 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800914 SLOGE("EVP_EncryptUpdate failed\n");
915 return -1;
916 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800917 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800918 SLOGE("EVP_EncryptFinal failed\n");
919 return -1;
920 }
921
922 if (encrypted_len + final_len != KEY_LEN_BYTES) {
923 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
924 return -1;
925 } else {
926 return 0;
927 }
928}
929
JP Abgrall7bdfa522013-11-15 13:42:56 -0800930static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
Ken Sumralle8744072011-01-18 22:01:55 -0800931 unsigned char *encrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700932 unsigned char *decrypted_master_key,
933 kdf_func kdf, void *kdf_params)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800934{
935 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 -0800936 EVP_CIPHER_CTX d_ctx;
937 int decrypted_len, final_len;
938
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800939 /* Turn the password into a key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700940 kdf(passwd, salt, ikey, kdf_params);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800941
942 /* Initialize the decryption engine */
943 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
944 return -1;
945 }
946 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
947 /* Decrypt the master key */
948 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
949 encrypted_master_key, KEY_LEN_BYTES)) {
950 return -1;
951 }
952 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
953 return -1;
954 }
955
956 if (decrypted_len + final_len != KEY_LEN_BYTES) {
957 return -1;
958 } else {
959 return 0;
960 }
961}
962
Kenny Rootc4c70f12013-06-14 12:11:38 -0700963static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800964{
Kenny Rootc4c70f12013-06-14 12:11:38 -0700965 if (ftr->kdf_type == KDF_SCRYPT) {
966 *kdf = scrypt;
967 *kdf_params = ftr;
968 } else {
969 *kdf = pbkdf2;
970 *kdf_params = NULL;
971 }
972}
973
JP Abgrall7bdfa522013-11-15 13:42:56 -0800974static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700975 struct crypt_mnt_ftr *crypt_ftr)
976{
977 kdf_func kdf;
978 void *kdf_params;
979 int ret;
980
981 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
JP Abgrall7bdfa522013-11-15 13:42:56 -0800982 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, decrypted_master_key, kdf,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700983 kdf_params);
984 if (ret != 0) {
985 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -0700986 }
987
988 return ret;
989}
990
991static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
992 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800993 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -0800994 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800995 EVP_CIPHER_CTX e_ctx;
996 int encrypted_len, final_len;
997
998 /* Get some random bits for a key */
999 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001000 read(fd, key_buf, sizeof(key_buf));
1001 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001002 close(fd);
1003
1004 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001005 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001006}
1007
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001008static int wait_and_unmount(char *mountpoint)
1009{
1010 int i, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001011#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001012
1013 /* Now umount the tmpfs filesystem */
1014 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
1015 if (umount(mountpoint)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001016 if (errno == EINVAL) {
1017 /* EINVAL is returned if the directory is not a mountpoint,
1018 * i.e. there is no filesystem mounted there. So just get out.
1019 */
1020 break;
1021 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001022 sleep(1);
1023 i++;
1024 } else {
1025 break;
1026 }
1027 }
1028
1029 if (i < WAIT_UNMOUNT_COUNT) {
1030 SLOGD("unmounting %s succeeded\n", mountpoint);
1031 rc = 0;
1032 } else {
1033 SLOGE("unmounting %s failed\n", mountpoint);
1034 rc = -1;
1035 }
1036
1037 return rc;
1038}
1039
Ken Sumrallc5872692013-05-14 15:26:31 -07001040#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001041static int prep_data_fs(void)
1042{
1043 int i;
1044
1045 /* Do the prep of the /data filesystem */
1046 property_set("vold.post_fs_data_done", "0");
1047 property_set("vold.decrypt", "trigger_post_fs_data");
1048 SLOGD("Just triggered post_fs_data\n");
1049
Ken Sumrallc5872692013-05-14 15:26:31 -07001050 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001051 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001052 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001053
1054 property_get("vold.post_fs_data_done", p, "0");
1055 if (*p == '1') {
1056 break;
1057 } else {
1058 usleep(250000);
1059 }
1060 }
1061 if (i == DATA_PREP_TIMEOUT) {
1062 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001063 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001064 return -1;
1065 } else {
1066 SLOGD("post_fs_data done\n");
1067 return 0;
1068 }
1069}
1070
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001071int cryptfs_restart(void)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001072{
1073 char fs_type[32];
1074 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001075 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001076 char fs_options[256];
1077 unsigned long mnt_flags;
1078 struct stat statbuf;
1079 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001080 static int restart_successful = 0;
1081
1082 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001083 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001084 SLOGE("Encrypted filesystem not validated, aborting");
1085 return -1;
1086 }
1087
1088 if (restart_successful) {
1089 SLOGE("System already restarted with encrypted disk, aborting");
1090 return -1;
1091 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001092
1093 /* Here is where we shut down the framework. The init scripts
1094 * start all services in one of three classes: core, main or late_start.
1095 * On boot, we start core and main. Now, we stop main, but not core,
1096 * as core includes vold and a few other really important things that
1097 * we need to keep running. Once main has stopped, we should be able
1098 * to umount the tmpfs /data, then mount the encrypted /data.
1099 * We then restart the class main, and also the class late_start.
1100 * At the moment, I've only put a few things in late_start that I know
1101 * are not needed to bring up the framework, and that also cause problems
1102 * with unmounting the tmpfs /data, but I hope to add add more services
1103 * to the late_start class as we optimize this to decrease the delay
1104 * till the user is asked for the password to the filesystem.
1105 */
1106
1107 /* The init files are setup to stop the class main when vold.decrypt is
1108 * set to trigger_reset_main.
1109 */
1110 property_set("vold.decrypt", "trigger_reset_main");
1111 SLOGD("Just asked init to shut down class main\n");
1112
Ken Sumrall92736ef2012-10-17 20:57:14 -07001113 /* Ugh, shutting down the framework is not synchronous, so until it
1114 * can be fixed, this horrible hack will wait a moment for it all to
1115 * shut down before proceeding. Without it, some devices cannot
1116 * restart the graphics services.
1117 */
1118 sleep(2);
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001119
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001120 /* Now that the framework is shutdown, we should be able to umount()
1121 * the tmpfs filesystem, and mount the real one.
1122 */
1123
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001124 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1125 if (strlen(crypto_blkdev) == 0) {
1126 SLOGE("fs_crypto_blkdev not set\n");
1127 return -1;
1128 }
1129
Ken Sumralle5032c42012-04-01 23:58:44 -07001130 if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001131 /* If ro.crypto.readonly is set to 1, mount the decrypted
1132 * filesystem readonly. This is used when /data is mounted by
1133 * recovery mode.
1134 */
1135 char ro_prop[PROPERTY_VALUE_MAX];
1136 property_get("ro.crypto.readonly", ro_prop, "");
1137 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1138 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1139 rec->flags |= MS_RDONLY;
1140 }
1141
Ken Sumralle5032c42012-04-01 23:58:44 -07001142 /* If that succeeded, then mount the decrypted filesystem */
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001143 fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001144
Ken Sumralle5032c42012-04-01 23:58:44 -07001145 property_set("vold.decrypt", "trigger_load_persist_props");
1146 /* Create necessary paths on /data */
1147 if (prep_data_fs()) {
1148 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001149 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001150
1151 /* startup service classes main and late_start */
1152 property_set("vold.decrypt", "trigger_restart_framework");
1153 SLOGD("Just triggered restart_framework\n");
1154
1155 /* Give it a few moments to get started */
1156 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001157 }
1158
Ken Sumrall0cc16632011-01-18 20:32:26 -08001159 if (rc == 0) {
1160 restart_successful = 1;
1161 }
1162
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001163 return rc;
1164}
1165
Mark Salyzyn3e971272014-01-21 13:27:04 -08001166static int do_crypto_complete(char *mount_point UNUSED)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001167{
1168 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001169 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001170 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001171
1172 property_get("ro.crypto.state", encrypted_state, "");
1173 if (strcmp(encrypted_state, "encrypted") ) {
1174 SLOGE("not running with encryption, aborting");
1175 return 1;
1176 }
1177
Ken Sumrall160b4d62013-04-22 12:15:39 -07001178 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001179 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001180
Ken Sumralle1a45852011-12-14 21:24:27 -08001181 /*
1182 * Only report this error if key_loc is a file and it exists.
1183 * If the device was never encrypted, and /data is not mountable for
1184 * some reason, returning 1 should prevent the UI from presenting the
1185 * a "enter password" screen, or worse, a "press button to wipe the
1186 * device" screen.
1187 */
1188 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1189 SLOGE("master key file does not exist, aborting");
1190 return 1;
1191 } else {
1192 SLOGE("Error getting crypt footer and key\n");
1193 return -1;
1194 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001195 }
1196
1197 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1198 SLOGE("Encryption process didn't finish successfully\n");
1199 return -2; /* -2 is the clue to the UI that there is no usable data on the disk,
1200 * and give the user an option to wipe the disk */
1201 }
1202
1203 /* We passed the test! We shall diminish, and return to the west */
1204 return 0;
1205}
1206
Ken Sumrall29d8da82011-05-18 17:20:07 -07001207static int test_mount_encrypted_fs(char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001208{
1209 struct crypt_mnt_ftr crypt_ftr;
1210 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001211 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001212 char crypto_blkdev[MAXPATHLEN];
1213 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001214 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001215 unsigned int orig_failed_decrypt_count;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001216 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001217 int rc;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001218 kdf_func kdf;
1219 void *kdf_params;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001220
Ken Sumrall0cc16632011-01-18 20:32:26 -08001221 property_get("ro.crypto.state", encrypted_state, "");
Jason parks70a4b3f2011-01-28 10:10:47 -06001222 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001223 SLOGE("encrypted fs already validated or not running with encryption, aborting");
1224 return -1;
1225 }
1226
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001227 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001228
Ken Sumrall160b4d62013-04-22 12:15:39 -07001229 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001230 SLOGE("Error getting crypt footer and key\n");
1231 return -1;
1232 }
Ken Sumralld33d4172011-02-01 00:49:13 -08001233
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001234 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr.fs_size);
1235 orig_failed_decrypt_count = crypt_ftr.failed_decrypt_count;
1236
1237 if (! (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001238 if (decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr)) {
1239 SLOGE("Failed to decrypt master key\n");
1240 return -1;
1241 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001242 }
1243
1244 if (create_crypto_blk_dev(&crypt_ftr, decrypted_master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -07001245 real_blkdev, crypto_blkdev, label)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001246 SLOGE("Error creating decrypted block device\n");
1247 return -1;
1248 }
1249
Alex Klyubin707795a2013-05-10 15:17:07 -07001250 /* If init detects an encrypted filesystem, it writes a file for each such
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001251 * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
1252 * files and passes that data to me */
1253 /* Create a tmp mount point to try mounting the decryptd fs
1254 * Since we're here, the mount_point should be a tmpfs filesystem, so make
1255 * a directory in it to test mount the decrypted filesystem.
1256 */
1257 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1258 mkdir(tmp_mount_point, 0755);
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001259 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001260 SLOGE("Error temp mounting decrypted block device\n");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001261 delete_crypto_blk_dev(label);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001262 crypt_ftr.failed_decrypt_count++;
1263 } else {
1264 /* Success, so just umount and we'll mount it properly when we restart
1265 * the framework.
1266 */
1267 umount(tmp_mount_point);
1268 crypt_ftr.failed_decrypt_count = 0;
1269 }
1270
1271 if (orig_failed_decrypt_count != crypt_ftr.failed_decrypt_count) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001272 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001273 }
1274
1275 if (crypt_ftr.failed_decrypt_count) {
1276 /* We failed to mount the device, so return an error */
1277 rc = crypt_ftr.failed_decrypt_count;
1278
1279 } else {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001280 /* Woot! Success! Save the name of the crypto block device
1281 * so we can mount it when restarting the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001282 */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001283 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001284
1285 /* Also save a the master key so we can reencrypted the key
1286 * the key when we want to change the password on it.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001287 */
Jason parks70a4b3f2011-01-28 10:10:47 -06001288 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001289 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001290 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001291 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001292 rc = 0;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001293 /*
1294 * Upgrade if we're not using the latest KDF.
1295 */
1296 if (crypt_ftr.kdf_type != KDF_SCRYPT) {
1297 crypt_ftr.kdf_type = KDF_SCRYPT;
1298 rc = encrypt_master_key(passwd, crypt_ftr.salt, saved_master_key, crypt_ftr.master_key,
1299 &crypt_ftr);
1300 if (!rc) {
1301 rc = put_crypt_ftr_and_key(&crypt_ftr);
1302 }
1303 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1304 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001305 }
1306
1307 return rc;
1308}
1309
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001310/* Called by vold when it wants to undo the crypto mapping of a volume it
1311 * manages. This is usually in response to a factory reset, when we want
1312 * to undo the crypto mapping so the volume is formatted in the clear.
1313 */
1314int cryptfs_revert_volume(const char *label)
1315{
1316 return delete_crypto_blk_dev((char *)label);
1317}
1318
Ken Sumrall29d8da82011-05-18 17:20:07 -07001319/*
1320 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1321 * Setup a dm-crypt mapping, use the saved master key from
1322 * setting up the /data mapping, and return the new device path.
1323 */
1324int cryptfs_setup_volume(const char *label, int major, int minor,
1325 char *crypto_sys_path, unsigned int max_path,
1326 int *new_major, int *new_minor)
1327{
1328 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1329 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001330 struct stat statbuf;
1331 int nr_sec, fd;
1332
1333 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1334
Ken Sumrall160b4d62013-04-22 12:15:39 -07001335 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001336
1337 /* Update the fs_size field to be the size of the volume */
1338 fd = open(real_blkdev, O_RDONLY);
1339 nr_sec = get_blkdev_size(fd);
1340 close(fd);
1341 if (nr_sec == 0) {
1342 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1343 return -1;
1344 }
1345
1346 sd_crypt_ftr.fs_size = nr_sec;
1347 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1348 crypto_blkdev, label);
1349
1350 stat(crypto_blkdev, &statbuf);
1351 *new_major = MAJOR(statbuf.st_rdev);
1352 *new_minor = MINOR(statbuf.st_rdev);
1353
1354 /* Create path to sys entry for this block device */
1355 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1356
1357 return 0;
1358}
1359
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001360int cryptfs_crypto_complete(void)
1361{
1362 return do_crypto_complete("/data");
1363}
1364
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001365int cryptfs_check_passwd(char *passwd)
1366{
1367 int rc = -1;
1368
Ken Sumrall29d8da82011-05-18 17:20:07 -07001369 rc = test_mount_encrypted_fs(passwd, DATA_MNT_POINT, "userdata");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001370
1371 return rc;
1372}
1373
Ken Sumrall3ad90722011-10-04 20:38:29 -07001374int cryptfs_verify_passwd(char *passwd)
1375{
1376 struct crypt_mnt_ftr crypt_ftr;
1377 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001378 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001379 char encrypted_state[PROPERTY_VALUE_MAX];
1380 int rc;
1381
1382 property_get("ro.crypto.state", encrypted_state, "");
1383 if (strcmp(encrypted_state, "encrypted") ) {
1384 SLOGE("device not encrypted, aborting");
1385 return -2;
1386 }
1387
1388 if (!master_key_saved) {
1389 SLOGE("encrypted fs not yet mounted, aborting");
1390 return -1;
1391 }
1392
1393 if (!saved_mount_point) {
1394 SLOGE("encrypted fs failed to save mount point, aborting");
1395 return -1;
1396 }
1397
Ken Sumrall160b4d62013-04-22 12:15:39 -07001398 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001399 SLOGE("Error getting crypt footer and key\n");
1400 return -1;
1401 }
1402
1403 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1404 /* If the device has no password, then just say the password is valid */
1405 rc = 0;
1406 } else {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001407 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001408 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1409 /* They match, the password is correct */
1410 rc = 0;
1411 } else {
1412 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1413 sleep(1);
1414 rc = 1;
1415 }
1416 }
1417
1418 return rc;
1419}
1420
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001421/* Initialize a crypt_mnt_ftr structure. The keysize is
1422 * defaulted to 16 bytes, and the filesystem size to 0.
1423 * Presumably, at a minimum, the caller will update the
1424 * filesystem size and crypto_type_name after calling this function.
1425 */
1426static void cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
1427{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001428 off64_t off;
1429
1430 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001431 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001432 ftr->major_version = CURRENT_MAJOR_VERSION;
1433 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001434 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001435 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001436
Kenny Rootc4c70f12013-06-14 12:11:38 -07001437 ftr->kdf_type = KDF_SCRYPT;
1438 get_device_scrypt_params(ftr);
1439
Ken Sumrall160b4d62013-04-22 12:15:39 -07001440 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1441 if (get_crypt_ftr_info(NULL, &off) == 0) {
1442 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1443 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1444 ftr->persist_data_size;
1445 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001446}
1447
Ken Sumrall29d8da82011-05-18 17:20:07 -07001448static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001449{
Ken Sumralle550f782013-08-20 13:48:23 -07001450 const char *args[10];
1451 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1452 int num_args;
1453 int status;
1454 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001455 int rc = -1;
1456
Ken Sumrall29d8da82011-05-18 17:20:07 -07001457 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001458 args[0] = "/system/bin/make_ext4fs";
1459 args[1] = "-a";
1460 args[2] = "/data";
1461 args[3] = "-l";
1462 snprintf(size_str, sizeof(size_str), "%lld", size * 512);
1463 args[4] = size_str;
1464 args[5] = crypto_blkdev;
1465 num_args = 6;
1466 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1467 args[0], args[1], args[2], args[3], args[4], args[5]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001468 } else if (type== FAT_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001469 args[0] = "/system/bin/newfs_msdos";
1470 args[1] = "-F";
1471 args[2] = "32";
1472 args[3] = "-O";
1473 args[4] = "android";
1474 args[5] = "-c";
1475 args[6] = "8";
1476 args[7] = "-s";
1477 snprintf(size_str, sizeof(size_str), "%lld", size);
1478 args[8] = size_str;
1479 args[9] = crypto_blkdev;
1480 num_args = 10;
1481 SLOGI("Making empty filesystem with command %s %s %s %s %s %s %s %s %s %s\n",
1482 args[0], args[1], args[2], args[3], args[4], args[5],
1483 args[6], args[7], args[8], args[9]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001484 } else {
1485 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1486 return -1;
1487 }
1488
Ken Sumralle550f782013-08-20 13:48:23 -07001489 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1490
1491 if (tmp != 0) {
1492 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001493 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07001494 if (WIFEXITED(status)) {
1495 if (WEXITSTATUS(status)) {
1496 SLOGE("Error creating filesystem on %s, exit status %d ",
1497 crypto_blkdev, WEXITSTATUS(status));
1498 } else {
1499 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
1500 rc = 0;
1501 }
1502 } else {
1503 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
1504 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001505 }
1506
1507 return rc;
1508}
1509
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001510#define CRYPT_INPLACE_BUFSIZE 4096
1511#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / 512)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001512
1513/* aligned 32K writes tends to make flash happy.
1514 * SD card association recommends it.
1515 */
1516#define BLOCKS_AT_A_TIME 8
1517
1518struct encryptGroupsData
1519{
1520 int realfd;
1521 int cryptofd;
1522 off64_t numblocks;
1523 off64_t one_pct, cur_pct, new_pct;
1524 off64_t blocks_already_done, tot_numblocks;
1525 char* real_blkdev, * crypto_blkdev;
1526 int count;
1527 off64_t offset;
1528 char* buffer;
1529};
1530
1531static void update_progress(struct encryptGroupsData* data)
1532{
1533 data->blocks_already_done++;
1534 data->new_pct = data->blocks_already_done / data->one_pct;
1535 if (data->new_pct > data->cur_pct) {
1536 char buf[8];
1537 data->cur_pct = data->new_pct;
1538 snprintf(buf, sizeof(buf), "%lld", data->cur_pct);
1539 property_set("vold.encrypt_progress", buf);
1540 }
1541}
1542
1543static int flush_outstanding_data(struct encryptGroupsData* data)
1544{
1545 if (data->count == 0) {
1546 return 0;
1547 }
1548
1549 SLOGV("Copying %d blocks at offset %llx", data->count, data->offset);
1550
1551 if (pread64(data->realfd, data->buffer,
1552 info.block_size * data->count, data->offset)
1553 <= 0) {
1554 SLOGE("Error reading real_blkdev %s for inplace encrypt",
1555 data->real_blkdev);
1556 return -1;
1557 }
1558
1559 if (pwrite64(data->cryptofd, data->buffer,
1560 info.block_size * data->count, data->offset)
1561 <= 0) {
1562 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
1563 data->crypto_blkdev);
1564 return -1;
1565 }
1566
1567 data->count = 0;
1568 return 0;
1569}
1570
1571static int encrypt_groups(struct encryptGroupsData* data)
1572{
1573 unsigned int i;
1574 u8 *block_bitmap = 0;
1575 unsigned int block;
1576 off64_t ret;
1577 int rc = -1;
1578
1579 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
1580 if (!data->buffer) {
1581 SLOGE("Failed to allocate crypto buffer");
1582 goto errout;
1583 }
1584
1585 block_bitmap = malloc(info.block_size);
1586 if (!block_bitmap) {
1587 SLOGE("failed to allocate block bitmap");
1588 goto errout;
1589 }
1590
1591 for (i = 0; i < aux_info.groups; ++i) {
1592 SLOGI("Encrypting group %d", i);
1593
1594 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
1595 u32 block_count = min(info.blocks_per_group,
1596 aux_info.len_blocks - first_block);
1597
1598 off64_t offset = (u64)info.block_size
1599 * aux_info.bg_desc[i].bg_block_bitmap;
1600
1601 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
1602 if (ret != (int)info.block_size) {
1603 SLOGE("failed to read all of block group bitmap %d", i);
1604 goto errout;
1605 }
1606
1607 offset = (u64)info.block_size * first_block;
1608
1609 data->count = 0;
1610
1611 for (block = 0; block < block_count; block++) {
1612 update_progress(data);
1613 if (bitmap_get_bit(block_bitmap, block)) {
1614 if (data->count == 0) {
1615 data->offset = offset;
1616 }
1617 data->count++;
1618 } else {
1619 if (flush_outstanding_data(data)) {
1620 goto errout;
1621 }
1622 }
1623
1624 offset += info.block_size;
1625
1626 /* Write data if we are aligned or buffer size reached */
1627 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
1628 || data->count == BLOCKS_AT_A_TIME) {
1629 if (flush_outstanding_data(data)) {
1630 goto errout;
1631 }
1632 }
1633 }
1634 if (flush_outstanding_data(data)) {
1635 goto errout;
1636 }
1637 }
1638
1639 rc = 0;
1640
1641errout:
1642 free(data->buffer);
1643 free(block_bitmap);
1644 return rc;
1645}
1646
1647static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
1648 char *real_blkdev,
1649 off64_t size,
1650 off64_t *size_already_done,
1651 off64_t tot_size)
1652{
1653 int i;
1654 struct encryptGroupsData data;
1655 int rc = -1;
1656
1657 memset(&data, 0, sizeof(data));
1658 data.real_blkdev = real_blkdev;
1659 data.crypto_blkdev = crypto_blkdev;
1660
1661 if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
1662 SLOGE("Error opening real_blkdev %s for inplace encrypt\n",
1663 real_blkdev);
1664 goto errout;
1665 }
1666
1667 if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
1668 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n",
1669 crypto_blkdev);
1670 goto errout;
1671 }
1672
1673 if (setjmp(setjmp_env)) {
1674 SLOGE("Reading extent caused an exception");
1675 goto errout;
1676 }
1677
1678 if (read_ext(data.realfd, 0) != 0) {
1679 SLOGE("Failed to read extent");
1680 goto errout;
1681 }
1682
1683 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
1684 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
1685 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
1686
1687 SLOGI("Encrypting filesystem in place...");
1688
1689 data.one_pct = data.tot_numblocks / 100;
1690 data.cur_pct = 0;
1691
1692 rc = encrypt_groups(&data);
1693 if (rc) {
1694 SLOGE("Error encrypting groups");
1695 goto errout;
1696 }
1697
1698 *size_already_done += size;
1699 rc = 0;
1700
1701errout:
1702 close(data.realfd);
1703 close(data.cryptofd);
1704
1705 return rc;
1706}
1707
1708static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
1709 off64_t size, off64_t *size_already_done,
1710 off64_t tot_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001711{
1712 int realfd, cryptofd;
1713 char *buf[CRYPT_INPLACE_BUFSIZE];
1714 int rc = -1;
1715 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001716 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001717 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001718
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001719 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
1720 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
1721 return -1;
1722 }
1723
1724 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
1725 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1726 close(realfd);
1727 return -1;
1728 }
1729
1730 /* This is pretty much a simple loop of reading 4K, and writing 4K.
1731 * The size passed in is the number of 512 byte sectors in the filesystem.
1732 * So compute the number of whole 4K blocks we should read/write,
1733 * and the remainder.
1734 */
1735 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
1736 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001737 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
1738 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001739
1740 SLOGE("Encrypting filesystem in place...");
1741
Ken Sumrall29d8da82011-05-18 17:20:07 -07001742 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001743 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001744 /* process the majority of the filesystem in blocks */
1745 for (i=0; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001746 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001747 if (new_pct > cur_pct) {
1748 char buf[8];
1749
1750 cur_pct = new_pct;
1751 snprintf(buf, sizeof(buf), "%lld", cur_pct);
1752 property_set("vold.encrypt_progress", buf);
1753 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001754 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1755 SLOGE("Error reading real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1756 goto errout;
1757 }
1758 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1759 SLOGE("Error writing crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1760 goto errout;
1761 }
1762 }
1763
1764 /* Do any remaining sectors */
1765 for (i=0; i<remainder; i++) {
1766 if (unix_read(realfd, buf, 512) <= 0) {
1767 SLOGE("Error reading rival sectors from real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1768 goto errout;
1769 }
1770 if (unix_write(cryptofd, buf, 512) <= 0) {
1771 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1772 goto errout;
1773 }
1774 }
1775
Ken Sumrall29d8da82011-05-18 17:20:07 -07001776 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001777 rc = 0;
1778
1779errout:
1780 close(realfd);
1781 close(cryptofd);
1782
1783 return rc;
1784}
1785
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001786static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
1787 off64_t size, off64_t *size_already_done,
1788 off64_t tot_size)
1789{
1790 if (cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
1791 size, size_already_done, tot_size) == 0) {
1792 return 0;
1793 }
1794
1795 return cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
1796 size, size_already_done, tot_size);
1797}
1798
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001799#define CRYPTO_ENABLE_WIPE 1
1800#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001801
1802#define FRAMEWORK_BOOT_WAIT 60
1803
Ken Sumrall29d8da82011-05-18 17:20:07 -07001804static inline int should_encrypt(struct volume_info *volume)
1805{
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001806 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
Ken Sumrall29d8da82011-05-18 17:20:07 -07001807 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
1808}
1809
JP Abgrall502dc742013-11-01 13:06:20 -07001810int cryptfs_enable(char *howarg, char *passwd, int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001811{
1812 int how = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001813 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN], sd_crypto_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07001814 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001815 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07001816 int rc=-1, fd, i, ret;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001817 struct crypt_mnt_ftr crypt_ftr, sd_crypt_ftr;;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001818 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001819 char tmpfs_options[PROPERTY_VALUE_MAX];
1820 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001821 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07001822 char key_loc[PROPERTY_VALUE_MAX];
1823 char fuse_sdcard[PROPERTY_VALUE_MAX];
1824 char *sd_mnt_point;
1825 char sd_blk_dev[256] = { 0 };
1826 int num_vols;
1827 struct volume_info *vol_list = 0;
1828 off64_t cur_encryption_done=0, tot_encryption_size=0;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001829
1830 property_get("ro.crypto.state", encrypted_state, "");
JP Abgrall502dc742013-11-01 13:06:20 -07001831 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001832 SLOGE("Device is already running encrypted, aborting");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001833 goto error_unencrypted;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001834 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001835
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001836 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001837
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001838 if (!strcmp(howarg, "wipe")) {
1839 how = CRYPTO_ENABLE_WIPE;
1840 } else if (! strcmp(howarg, "inplace")) {
1841 how = CRYPTO_ENABLE_INPLACE;
1842 } else {
1843 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08001844 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001845 }
1846
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001847 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001848
Ken Sumrall3ed82362011-01-28 23:31:16 -08001849 /* Get the size of the real block device */
1850 fd = open(real_blkdev, O_RDONLY);
1851 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
1852 SLOGE("Cannot get size of block device %s\n", real_blkdev);
1853 goto error_unencrypted;
1854 }
1855 close(fd);
1856
1857 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001858 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001859 unsigned int fs_size_sec, max_fs_size_sec;
1860
1861 fs_size_sec = get_fs_size(real_blkdev);
1862 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1863
1864 if (fs_size_sec > max_fs_size_sec) {
1865 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
1866 goto error_unencrypted;
1867 }
1868 }
1869
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001870 /* Get a wakelock as this may take a while, and we don't want the
1871 * device to sleep on us. We'll grab a partial wakelock, and if the UI
1872 * wants to keep the screen on, it can grab a full wakelock.
1873 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001874 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001875 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
1876
Jeff Sharkey7382f812012-08-23 14:08:59 -07001877 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07001878 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07001879 if (!sd_mnt_point) {
1880 sd_mnt_point = getenv("EXTERNAL_STORAGE");
1881 }
1882 if (!sd_mnt_point) {
1883 sd_mnt_point = "/mnt/sdcard";
1884 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07001885
1886 num_vols=vold_getNumDirectVolumes();
1887 vol_list = malloc(sizeof(struct volume_info) * num_vols);
1888 vold_getDirectVolumeList(vol_list);
1889
1890 for (i=0; i<num_vols; i++) {
1891 if (should_encrypt(&vol_list[i])) {
1892 fd = open(vol_list[i].blk_dev, O_RDONLY);
1893 if ( (vol_list[i].size = get_blkdev_size(fd)) == 0) {
1894 SLOGE("Cannot get size of block device %s\n", vol_list[i].blk_dev);
1895 goto error_unencrypted;
1896 }
1897 close(fd);
1898
Ken Sumrall3b170052011-07-11 15:38:57 -07001899 ret=vold_disableVol(vol_list[i].label);
Ken Sumrall319b1042011-06-14 14:01:55 -07001900 if ((ret < 0) && (ret != UNMOUNT_NOT_MOUNTED_ERR)) {
1901 /* -2 is returned when the device exists but is not currently mounted.
1902 * ignore the error and continue. */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001903 SLOGE("Failed to unmount volume %s\n", vol_list[i].label);
1904 goto error_unencrypted;
1905 }
1906 }
1907 }
1908
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001909 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001910 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001911 */
1912 property_set("vold.decrypt", "trigger_shutdown_framework");
1913 SLOGD("Just asked init to shut down class main\n");
1914
Ken Sumrall425524d2012-06-14 20:55:28 -07001915 if (vold_unmountAllAsecs()) {
1916 /* Just report the error. If any are left mounted,
1917 * umounting /data below will fail and handle the error.
1918 */
1919 SLOGE("Error unmounting internal asecs");
1920 }
1921
Ken Sumrall29d8da82011-05-18 17:20:07 -07001922 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
1923 if (!strcmp(fuse_sdcard, "true")) {
1924 /* This is a device using the fuse layer to emulate the sdcard semantics
1925 * on top of the userdata partition. vold does not manage it, it is managed
1926 * by the sdcard service. The sdcard service was killed by the property trigger
1927 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
1928 * unlike the case for vold managed devices above.
1929 */
1930 if (wait_and_unmount(sd_mnt_point)) {
1931 goto error_shutting_down;
1932 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001933 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001934
1935 /* Now unmount the /data partition. */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001936 if (wait_and_unmount(DATA_MNT_POINT)) {
JP Abgrall502dc742013-11-01 13:06:20 -07001937 if (allow_reboot) {
1938 goto error_shutting_down;
1939 } else {
1940 goto error_unencrypted;
1941 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001942 }
1943
1944 /* Do extra work for a better UX when doing the long inplace encryption */
1945 if (how == CRYPTO_ENABLE_INPLACE) {
1946 /* Now that /data is unmounted, we need to mount a tmpfs
1947 * /data, set a property saying we're doing inplace encryption,
1948 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001949 */
Ken Sumralle5032c42012-04-01 23:58:44 -07001950 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001951 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001952 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001953 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08001954 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001955
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001956 /* restart the framework. */
1957 /* Create necessary paths on /data */
1958 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001959 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001960 }
1961
Ken Sumrall92736ef2012-10-17 20:57:14 -07001962 /* Ugh, shutting down the framework is not synchronous, so until it
1963 * can be fixed, this horrible hack will wait a moment for it all to
1964 * shut down before proceeding. Without it, some devices cannot
1965 * restart the graphics services.
1966 */
1967 sleep(2);
1968
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001969 /* startup service classes main and late_start */
1970 property_set("vold.decrypt", "trigger_restart_min_framework");
1971 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001972
Ken Sumrall7df84122011-01-18 14:04:08 -08001973 /* OK, the framework is restarted and will soon be showing a
1974 * progress bar. Time to setup an encrypted mapping, and
1975 * either write a new filesystem, or encrypt in place updating
1976 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001977 */
1978 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001979
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001980 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001981 /* Initialize a crypt_mnt_ftr for the partition */
1982 cryptfs_init_crypt_mnt_ftr(&crypt_ftr);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001983
Ken Sumrall29d8da82011-05-18 17:20:07 -07001984 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
1985 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1986 } else {
1987 crypt_ftr.fs_size = nr_sec;
1988 }
Ken Sumralld33d4172011-02-01 00:49:13 -08001989 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001990 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
1991
1992 /* Make an encrypted master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001993 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001994 SLOGE("Cannot create encrypted master key\n");
JP Abgrall502dc742013-11-01 13:06:20 -07001995 goto error_shutting_down;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001996 }
1997
1998 /* Write the key to the end of the partition */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001999 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002000
Ken Sumrall160b4d62013-04-22 12:15:39 -07002001 /* If any persistent data has been remembered, save it.
2002 * If none, create a valid empty table and save that.
2003 */
2004 if (!persist_data) {
2005 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
2006 if (pdata) {
2007 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2008 persist_data = pdata;
2009 }
2010 }
2011 if (persist_data) {
2012 save_persistent_data();
2013 }
2014
JP Abgrall7bdfa522013-11-15 13:42:56 -08002015 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002016 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
2017 "userdata");
2018
Ken Sumrall128626f2011-06-28 18:45:14 -07002019 /* The size of the userdata partition, and add in the vold volumes below */
2020 tot_encryption_size = crypt_ftr.fs_size;
2021
Ken Sumrall29d8da82011-05-18 17:20:07 -07002022 /* setup crypto mapping for all encryptable volumes handled by vold */
2023 for (i=0; i<num_vols; i++) {
2024 if (should_encrypt(&vol_list[i])) {
2025 vol_list[i].crypt_ftr = crypt_ftr; /* gotta love struct assign */
2026 vol_list[i].crypt_ftr.fs_size = vol_list[i].size;
2027 create_crypto_blk_dev(&vol_list[i].crypt_ftr, decrypted_master_key,
2028 vol_list[i].blk_dev, vol_list[i].crypto_blkdev,
2029 vol_list[i].label);
Ken Sumrall128626f2011-06-28 18:45:14 -07002030 tot_encryption_size += vol_list[i].size;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002031 }
2032 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002033
2034 if (how == CRYPTO_ENABLE_WIPE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002035 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr.fs_size, EXT4_FS);
2036 /* Encrypt all encryptable volumes handled by vold */
2037 if (!rc) {
2038 for (i=0; i<num_vols; i++) {
2039 if (should_encrypt(&vol_list[i])) {
2040 rc = cryptfs_enable_wipe(vol_list[i].crypto_blkdev,
2041 vol_list[i].crypt_ftr.fs_size, FAT_FS);
2042 }
2043 }
2044 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002045 } else if (how == CRYPTO_ENABLE_INPLACE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002046 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr.fs_size,
2047 &cur_encryption_done, tot_encryption_size);
2048 /* Encrypt all encryptable volumes handled by vold */
2049 if (!rc) {
2050 for (i=0; i<num_vols; i++) {
2051 if (should_encrypt(&vol_list[i])) {
2052 rc = cryptfs_enable_inplace(vol_list[i].crypto_blkdev,
2053 vol_list[i].blk_dev,
2054 vol_list[i].crypt_ftr.fs_size,
2055 &cur_encryption_done, tot_encryption_size);
2056 }
2057 }
2058 }
2059 if (!rc) {
2060 /* The inplace routine never actually sets the progress to 100%
2061 * due to the round down nature of integer division, so set it here */
2062 property_set("vold.encrypt_progress", "100");
2063 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002064 } else {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002065 /* Shouldn't happen */
2066 SLOGE("cryptfs_enable: internal error, unknown option\n");
JP Abgrall502dc742013-11-01 13:06:20 -07002067 goto error_shutting_down;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002068 }
2069
2070 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002071 delete_crypto_blk_dev("userdata");
2072 for (i=0; i<num_vols; i++) {
2073 if (should_encrypt(&vol_list[i])) {
2074 delete_crypto_blk_dev(vol_list[i].label);
2075 }
2076 }
2077
2078 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002079
2080 if (! rc) {
2081 /* Success */
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002082
Ken Sumralld33d4172011-02-01 00:49:13 -08002083 /* Clear the encryption in progres flag in the footer */
2084 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002085 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002086
Ken Sumrall29d8da82011-05-18 17:20:07 -07002087 sleep(2); /* Give the UI a chance to show 100% progress */
Ken Sumralladfba362013-06-04 16:37:52 -07002088 cryptfs_reboot(0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002089 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002090 char value[PROPERTY_VALUE_MAX];
2091
Ken Sumrall319369a2012-06-27 16:30:18 -07002092 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002093 if (!strcmp(value, "1")) {
2094 /* wipe data if encryption failed */
2095 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
2096 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07002097 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002098 if (fd >= 0) {
2099 write(fd, "--wipe_data", strlen("--wipe_data") + 1);
2100 close(fd);
2101 } else {
2102 SLOGE("could not open /cache/recovery/command\n");
2103 }
Ken Sumralladfba362013-06-04 16:37:52 -07002104 cryptfs_reboot(1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002105 } else {
2106 /* set property to trigger dialog */
2107 property_set("vold.encrypt_progress", "error_partially_encrypted");
2108 release_wake_lock(lockid);
2109 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002110 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002111 }
2112
Ken Sumrall3ed82362011-01-28 23:31:16 -08002113 /* hrm, the encrypt step claims success, but the reboot failed.
2114 * This should not happen.
2115 * Set the property and return. Hope the framework can deal with it.
2116 */
2117 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002118 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002119 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002120
2121error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07002122 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002123 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002124 if (lockid[0]) {
2125 release_wake_lock(lockid);
2126 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002127 return -1;
2128
2129error_shutting_down:
2130 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2131 * but the framework is stopped and not restarted to show the error, so it's up to
2132 * vold to restart the system.
2133 */
2134 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Ken Sumralladfba362013-06-04 16:37:52 -07002135 cryptfs_reboot(0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002136
2137 /* shouldn't get here */
2138 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07002139 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002140 if (lockid[0]) {
2141 release_wake_lock(lockid);
2142 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002143 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002144}
2145
Jason parks70a4b3f2011-01-28 10:10:47 -06002146int cryptfs_changepw(char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002147{
2148 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002149 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002150
2151 /* This is only allowed after we've successfully decrypted the master key */
Jason parks70a4b3f2011-01-28 10:10:47 -06002152 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002153 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002154 return -1;
2155 }
2156
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002157 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002158 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall57b63e62011-01-17 18:29:19 -08002159 SLOGE("Error getting crypt footer and key");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002160 return -1;
2161 }
2162
Kenny Rootc4c70f12013-06-14 12:11:38 -07002163 encrypt_master_key(newpw, crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002164
Jason parks70a4b3f2011-01-28 10:10:47 -06002165 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002166 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002167
2168 return 0;
2169}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002170
2171static int persist_get_key(char *fieldname, char *value)
2172{
2173 unsigned int i;
2174
2175 if (persist_data == NULL) {
2176 return -1;
2177 }
2178 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2179 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2180 /* We found it! */
2181 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2182 return 0;
2183 }
2184 }
2185
2186 return -1;
2187}
2188
2189static int persist_set_key(char *fieldname, char *value, int encrypted)
2190{
2191 unsigned int i;
2192 unsigned int num;
2193 struct crypt_mnt_ftr crypt_ftr;
2194 unsigned int max_persistent_entries;
2195 unsigned int dsize;
2196
2197 if (persist_data == NULL) {
2198 return -1;
2199 }
2200
2201 /* If encrypted, use the values from the crypt_ftr, otherwise
2202 * use the values for the current spec.
2203 */
2204 if (encrypted) {
2205 if(get_crypt_ftr_and_key(&crypt_ftr)) {
2206 return -1;
2207 }
2208 dsize = crypt_ftr.persist_data_size;
2209 } else {
2210 dsize = CRYPT_PERSIST_DATA_SIZE;
2211 }
2212 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2213 sizeof(struct crypt_persist_entry);
2214
2215 num = persist_data->persist_valid_entries;
2216
2217 for (i = 0; i < num; i++) {
2218 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2219 /* We found an existing entry, update it! */
2220 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2221 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2222 return 0;
2223 }
2224 }
2225
2226 /* We didn't find it, add it to the end, if there is room */
2227 if (persist_data->persist_valid_entries < max_persistent_entries) {
2228 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2229 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2230 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2231 persist_data->persist_valid_entries++;
2232 return 0;
2233 }
2234
2235 return -1;
2236}
2237
2238/* Return the value of the specified field. */
2239int cryptfs_getfield(char *fieldname, char *value, int len)
2240{
2241 char temp_value[PROPERTY_VALUE_MAX];
2242 char real_blkdev[MAXPATHLEN];
2243 /* 0 is success, 1 is not encrypted,
2244 * -1 is value not set, -2 is any other error
2245 */
2246 int rc = -2;
2247
2248 if (persist_data == NULL) {
2249 load_persistent_data();
2250 if (persist_data == NULL) {
2251 SLOGE("Getfield error, cannot load persistent data");
2252 goto out;
2253 }
2254 }
2255
2256 if (!persist_get_key(fieldname, temp_value)) {
2257 /* We found it, copy it to the caller's buffer and return */
2258 strlcpy(value, temp_value, len);
2259 rc = 0;
2260 } else {
2261 /* Sadness, it's not there. Return the error */
2262 rc = -1;
2263 }
2264
2265out:
2266 return rc;
2267}
2268
2269/* Set the value of the specified field. */
2270int cryptfs_setfield(char *fieldname, char *value)
2271{
2272 struct crypt_persist_data stored_pdata;
2273 struct crypt_persist_data *pdata_p;
2274 struct crypt_mnt_ftr crypt_ftr;
2275 char encrypted_state[PROPERTY_VALUE_MAX];
2276 /* 0 is success, -1 is an error */
2277 int rc = -1;
2278 int encrypted = 0;
2279
2280 if (persist_data == NULL) {
2281 load_persistent_data();
2282 if (persist_data == NULL) {
2283 SLOGE("Setfield error, cannot load persistent data");
2284 goto out;
2285 }
2286 }
2287
2288 property_get("ro.crypto.state", encrypted_state, "");
2289 if (!strcmp(encrypted_state, "encrypted") ) {
2290 encrypted = 1;
2291 }
2292
2293 if (persist_set_key(fieldname, value, encrypted)) {
2294 goto out;
2295 }
2296
2297 /* If we are running encrypted, save the persistent data now */
2298 if (encrypted) {
2299 if (save_persistent_data()) {
2300 SLOGE("Setfield error, cannot save persistent data");
2301 goto out;
2302 }
2303 }
2304
2305 rc = 0;
2306
2307out:
2308 return rc;
2309}