blob: 266481d4ef8380d512ba6a0138d9341c1c0c6d08 [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>
24#include <sys/stat.h>
25#include <fcntl.h>
26#include <unistd.h>
27#include <stdio.h>
28#include <sys/ioctl.h>
29#include <linux/dm-ioctl.h>
30#include <libgen.h>
31#include <stdlib.h>
32#include <sys/param.h>
33#include <string.h>
34#include <sys/mount.h>
35#include <openssl/evp.h>
Ken Sumrall8ddbe402011-01-17 15:26:29 -080036#include <openssl/sha.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080037#include <errno.h>
Ken Sumrall3ed82362011-01-28 23:31:16 -080038#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070039#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070040#include <fs_mgr.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080041#include "cryptfs.h"
42#define LOG_TAG "Cryptfs"
43#include "cutils/log.h"
44#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070045#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080046#include "hardware_legacy/power.h"
Ken Sumrall29d8da82011-05-18 17:20:07 -070047#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070048#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070049#include "crypto_scrypt.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080050
51#define DM_CRYPT_BUF_SIZE 4096
Ken Sumrall8ddbe402011-01-17 15:26:29 -080052#define DATA_MNT_POINT "/data"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080053
Jason parks70a4b3f2011-01-28 10:10:47 -060054#define HASH_COUNT 2000
55#define KEY_LEN_BYTES 16
56#define IV_LEN_BYTES 16
57
Ken Sumrall29d8da82011-05-18 17:20:07 -070058#define KEY_IN_FOOTER "footer"
59
60#define EXT4_FS 1
61#define FAT_FS 2
62
Ken Sumralle919efe2012-09-29 17:07:41 -070063#define TABLE_LOAD_RETRIES 10
64
Ken Sumrall8f869aa2010-12-03 03:47:09 -080065char *me = "cryptfs";
66
Jason parks70a4b3f2011-01-28 10:10:47 -060067static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070068static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060069static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -070070static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -080071
72extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -080073
Ken Sumralladfba362013-06-04 16:37:52 -070074static void cryptfs_reboot(int recovery)
75{
76 if (recovery) {
77 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
78 } else {
79 property_set(ANDROID_RB_PROPERTY, "reboot");
80 }
81 sleep(20);
82
83 /* Shouldn't get here, reboot should happen before sleep times out */
84 return;
85}
86
Ken Sumrall8f869aa2010-12-03 03:47:09 -080087static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
88{
89 memset(io, 0, dataSize);
90 io->data_size = dataSize;
91 io->data_start = sizeof(struct dm_ioctl);
92 io->version[0] = 4;
93 io->version[1] = 0;
94 io->version[2] = 0;
95 io->flags = flags;
96 if (name) {
97 strncpy(io->name, name, sizeof(io->name));
98 }
99}
100
Kenny Rootc4c70f12013-06-14 12:11:38 -0700101/**
102 * Gets the default device scrypt parameters for key derivation time tuning.
103 * The parameters should lead to about one second derivation time for the
104 * given device.
105 */
106static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
107 const int default_params[] = SCRYPT_DEFAULTS;
108 int params[] = SCRYPT_DEFAULTS;
109 char paramstr[PROPERTY_VALUE_MAX];
110 char *token;
111 char *saveptr;
112 int i;
113
114 property_get(SCRYPT_PROP, paramstr, "");
115 if (paramstr[0] != '\0') {
116 /*
117 * The token we're looking for should be three integers separated by
118 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
119 */
120 for (token = strtok_r(paramstr, ":", &saveptr); token != NULL && i < 3;
121 i++, token = strtok_r(NULL, ":", &saveptr)) {
122 char *endptr;
123 params[i] = strtol(token, &endptr, 10);
124
125 /*
126 * Check that there was a valid number and it's 8-bit. If not,
127 * break out and the end check will take the default values.
128 */
129 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
130 break;
131 }
132 }
133
134 /*
135 * If there were not enough tokens or a token was malformed (not an
136 * integer), it will end up here and the default parameters can be
137 * taken.
138 */
139 if ((i != 3) || (token != NULL)) {
140 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
141 memcpy(params, default_params, sizeof(params));
142 }
143 }
144
145 ftr->N_factor = params[0];
146 ftr->r_factor = params[1];
147 ftr->p_factor = params[2];
148}
149
Ken Sumrall3ed82362011-01-28 23:31:16 -0800150static unsigned int get_fs_size(char *dev)
151{
152 int fd, block_size;
153 struct ext4_super_block sb;
154 off64_t len;
155
156 if ((fd = open(dev, O_RDONLY)) < 0) {
157 SLOGE("Cannot open device to get filesystem size ");
158 return 0;
159 }
160
161 if (lseek64(fd, 1024, SEEK_SET) < 0) {
162 SLOGE("Cannot seek to superblock");
163 return 0;
164 }
165
166 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
167 SLOGE("Cannot read superblock");
168 return 0;
169 }
170
171 close(fd);
172
173 block_size = 1024 << sb.s_log_block_size;
174 /* compute length in bytes */
175 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
176
177 /* return length in sectors */
178 return (unsigned int) (len / 512);
179}
180
Ken Sumrall160b4d62013-04-22 12:15:39 -0700181static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
182{
183 static int cached_data = 0;
184 static off64_t cached_off = 0;
185 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
186 int fd;
187 char key_loc[PROPERTY_VALUE_MAX];
188 char real_blkdev[PROPERTY_VALUE_MAX];
189 unsigned int nr_sec;
190 int rc = -1;
191
192 if (!cached_data) {
193 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
194
195 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
196 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
197 SLOGE("Cannot open real block device %s\n", real_blkdev);
198 return -1;
199 }
200
201 if ((nr_sec = get_blkdev_size(fd))) {
202 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
203 * encryption info footer and key, and plenty of bytes to spare for future
204 * growth.
205 */
206 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
207 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
208 cached_data = 1;
209 } else {
210 SLOGE("Cannot get size of block device %s\n", real_blkdev);
211 }
212 close(fd);
213 } else {
214 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
215 cached_off = 0;
216 cached_data = 1;
217 }
218 }
219
220 if (cached_data) {
221 if (metadata_fname) {
222 *metadata_fname = cached_metadata_fname;
223 }
224 if (off) {
225 *off = cached_off;
226 }
227 rc = 0;
228 }
229
230 return rc;
231}
232
Ken Sumralle8744072011-01-18 22:01:55 -0800233/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800234 * update the failed mount count but not change the key.
235 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700236static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800237{
238 int fd;
239 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700240 /* starting_off is set to the SEEK_SET offset
241 * where the crypto structure starts
242 */
243 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800244 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700245 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700246 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall3be890f2011-09-14 16:53:46 -0700247 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800248
Ken Sumrall160b4d62013-04-22 12:15:39 -0700249 if (get_crypt_ftr_info(&fname, &starting_off)) {
250 SLOGE("Unable to get crypt_ftr_info\n");
251 return -1;
252 }
253 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700254 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700255 return -1;
256 }
257 if ( (fd = open(fname, O_RDWR)) < 0) {
258 SLOGE("Cannot open footer file %s\n", fname);
259 return -1;
260 }
261
262 /* Seek to the start of the crypt footer */
263 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
264 SLOGE("Cannot seek to real block device footer\n");
265 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800266 }
267
268 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
269 SLOGE("Cannot write real block device footer\n");
270 goto errout;
271 }
272
Ken Sumrall3be890f2011-09-14 16:53:46 -0700273 fstat(fd, &statbuf);
274 /* If the keys are kept on a raw block device, do not try to truncate it. */
275 if (S_ISREG(statbuf.st_mode) && (key_loc[0] == '/')) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700276 if (ftruncate(fd, 0x4000)) {
Ken Sumrall3be890f2011-09-14 16:53:46 -0700277 SLOGE("Cannot set footer file size\n", fname);
Ken Sumralle8744072011-01-18 22:01:55 -0800278 goto errout;
279 }
280 }
281
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800282 /* Success! */
283 rc = 0;
284
285errout:
286 close(fd);
287 return rc;
288
289}
290
Ken Sumrall160b4d62013-04-22 12:15:39 -0700291static inline int unix_read(int fd, void* buff, int len)
292{
293 return TEMP_FAILURE_RETRY(read(fd, buff, len));
294}
295
296static inline int unix_write(int fd, const void* buff, int len)
297{
298 return TEMP_FAILURE_RETRY(write(fd, buff, len));
299}
300
301static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
302{
303 memset(pdata, 0, len);
304 pdata->persist_magic = PERSIST_DATA_MAGIC;
305 pdata->persist_valid_entries = 0;
306}
307
308/* A routine to update the passed in crypt_ftr to the lastest version.
309 * fd is open read/write on the device that holds the crypto footer and persistent
310 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
311 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
312 */
313static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
314{
Kenny Root7434b312013-06-14 11:29:53 -0700315 int orig_major = crypt_ftr->major_version;
316 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700317
Kenny Root7434b312013-06-14 11:29:53 -0700318 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
319 struct crypt_persist_data *pdata;
320 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700321
Kenny Rootc4c70f12013-06-14 12:11:38 -0700322 SLOGW("upgrading crypto footer to 1.1");
323
Kenny Root7434b312013-06-14 11:29:53 -0700324 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
325 if (pdata == NULL) {
326 SLOGE("Cannot allocate persisent data\n");
327 return;
328 }
329 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
330
331 /* Need to initialize the persistent data area */
332 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
333 SLOGE("Cannot seek to persisent data offset\n");
334 return;
335 }
336 /* Write all zeros to the first copy, making it invalid */
337 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
338
339 /* Write a valid but empty structure to the second copy */
340 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
341 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
342
343 /* Update the footer */
344 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
345 crypt_ftr->persist_data_offset[0] = pdata_offset;
346 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
347 crypt_ftr->minor_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700348 }
349
Kenny Rootc4c70f12013-06-14 12:11:38 -0700350 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version)) {
351 SLOGW("upgrading crypto footer to 1.2");
352 crypt_ftr->kdf_type = KDF_PBKDF2;
353 get_device_scrypt_params(crypt_ftr);
354 crypt_ftr->minor_version = 2;
355 }
356
Kenny Root7434b312013-06-14 11:29:53 -0700357 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
358 if (lseek64(fd, offset, SEEK_SET) == -1) {
359 SLOGE("Cannot seek to crypt footer\n");
360 return;
361 }
362 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700363 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700364}
365
366
367static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800368{
369 int fd;
370 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700371 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800372 int rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700373 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700374 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700375 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800376
Ken Sumrall160b4d62013-04-22 12:15:39 -0700377 if (get_crypt_ftr_info(&fname, &starting_off)) {
378 SLOGE("Unable to get crypt_ftr_info\n");
379 return -1;
380 }
381 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700382 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700383 return -1;
384 }
385 if ( (fd = open(fname, O_RDWR)) < 0) {
386 SLOGE("Cannot open footer file %s\n", fname);
387 return -1;
388 }
389
390 /* Make sure it's 16 Kbytes in length */
391 fstat(fd, &statbuf);
392 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
393 SLOGE("footer file %s is not the expected size!\n", fname);
394 goto errout;
395 }
396
397 /* Seek to the start of the crypt footer */
398 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
399 SLOGE("Cannot seek to real block device footer\n");
400 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800401 }
402
403 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
404 SLOGE("Cannot read real block device footer\n");
405 goto errout;
406 }
407
408 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700409 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800410 goto errout;
411 }
412
Kenny Rootc96a5f82013-06-14 12:08:28 -0700413 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
414 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
415 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800416 goto errout;
417 }
418
Kenny Rootc96a5f82013-06-14 12:08:28 -0700419 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
420 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
421 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800422 }
423
Ken Sumrall160b4d62013-04-22 12:15:39 -0700424 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
425 * copy on disk before returning.
426 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700427 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700428 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800429 }
430
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800431 /* Success! */
432 rc = 0;
433
434errout:
435 close(fd);
436 return rc;
437}
438
Ken Sumrall160b4d62013-04-22 12:15:39 -0700439static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
440{
441 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
442 crypt_ftr->persist_data_offset[1]) {
443 SLOGE("Crypt_ftr persist data regions overlap");
444 return -1;
445 }
446
447 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
448 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
449 return -1;
450 }
451
452 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
453 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
454 CRYPT_FOOTER_OFFSET) {
455 SLOGE("Persistent data extends past crypto footer");
456 return -1;
457 }
458
459 return 0;
460}
461
462static int load_persistent_data(void)
463{
464 struct crypt_mnt_ftr crypt_ftr;
465 struct crypt_persist_data *pdata = NULL;
466 char encrypted_state[PROPERTY_VALUE_MAX];
467 char *fname;
468 int found = 0;
469 int fd;
470 int ret;
471 int i;
472
473 if (persist_data) {
474 /* Nothing to do, we've already loaded or initialized it */
475 return 0;
476 }
477
478
479 /* If not encrypted, just allocate an empty table and initialize it */
480 property_get("ro.crypto.state", encrypted_state, "");
481 if (strcmp(encrypted_state, "encrypted") ) {
482 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
483 if (pdata) {
484 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
485 persist_data = pdata;
486 return 0;
487 }
488 return -1;
489 }
490
491 if(get_crypt_ftr_and_key(&crypt_ftr)) {
492 return -1;
493 }
494
495 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
496 SLOGE("Crypt_ftr version doesn't support persistent data");
497 return -1;
498 }
499
500 if (get_crypt_ftr_info(&fname, NULL)) {
501 return -1;
502 }
503
504 ret = validate_persistent_data_storage(&crypt_ftr);
505 if (ret) {
506 return -1;
507 }
508
509 fd = open(fname, O_RDONLY);
510 if (fd < 0) {
511 SLOGE("Cannot open %s metadata file", fname);
512 return -1;
513 }
514
515 if (persist_data == NULL) {
516 pdata = malloc(crypt_ftr.persist_data_size);
517 if (pdata == NULL) {
518 SLOGE("Cannot allocate memory for persistent data");
519 goto err;
520 }
521 }
522
523 for (i = 0; i < 2; i++) {
524 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
525 SLOGE("Cannot seek to read persistent data on %s", fname);
526 goto err2;
527 }
528 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
529 SLOGE("Error reading persistent data on iteration %d", i);
530 goto err2;
531 }
532 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
533 found = 1;
534 break;
535 }
536 }
537
538 if (!found) {
539 SLOGI("Could not find valid persistent data, creating");
540 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
541 }
542
543 /* Success */
544 persist_data = pdata;
545 close(fd);
546 return 0;
547
548err2:
549 free(pdata);
550
551err:
552 close(fd);
553 return -1;
554}
555
556static int save_persistent_data(void)
557{
558 struct crypt_mnt_ftr crypt_ftr;
559 struct crypt_persist_data *pdata;
560 char *fname;
561 off64_t write_offset;
562 off64_t erase_offset;
563 int found = 0;
564 int fd;
565 int ret;
566
567 if (persist_data == NULL) {
568 SLOGE("No persistent data to save");
569 return -1;
570 }
571
572 if(get_crypt_ftr_and_key(&crypt_ftr)) {
573 return -1;
574 }
575
576 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
577 SLOGE("Crypt_ftr version doesn't support persistent data");
578 return -1;
579 }
580
581 ret = validate_persistent_data_storage(&crypt_ftr);
582 if (ret) {
583 return -1;
584 }
585
586 if (get_crypt_ftr_info(&fname, NULL)) {
587 return -1;
588 }
589
590 fd = open(fname, O_RDWR);
591 if (fd < 0) {
592 SLOGE("Cannot open %s metadata file", fname);
593 return -1;
594 }
595
596 pdata = malloc(crypt_ftr.persist_data_size);
597 if (pdata == NULL) {
598 SLOGE("Cannot allocate persistant data");
599 goto err;
600 }
601
602 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
603 SLOGE("Cannot seek to read persistent data on %s", fname);
604 goto err2;
605 }
606
607 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
608 SLOGE("Error reading persistent data before save");
609 goto err2;
610 }
611
612 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
613 /* The first copy is the curent valid copy, so write to
614 * the second copy and erase this one */
615 write_offset = crypt_ftr.persist_data_offset[1];
616 erase_offset = crypt_ftr.persist_data_offset[0];
617 } else {
618 /* The second copy must be the valid copy, so write to
619 * the first copy, and erase the second */
620 write_offset = crypt_ftr.persist_data_offset[0];
621 erase_offset = crypt_ftr.persist_data_offset[1];
622 }
623
624 /* Write the new copy first, if successful, then erase the old copy */
625 if (lseek(fd, write_offset, SEEK_SET) < 0) {
626 SLOGE("Cannot seek to write persistent data");
627 goto err2;
628 }
629 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
630 (int) crypt_ftr.persist_data_size) {
631 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
632 SLOGE("Cannot seek to erase previous persistent data");
633 goto err2;
634 }
635 fsync(fd);
636 memset(pdata, 0, crypt_ftr.persist_data_size);
637 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
638 (int) crypt_ftr.persist_data_size) {
639 SLOGE("Cannot write to erase previous persistent data");
640 goto err2;
641 }
642 fsync(fd);
643 } else {
644 SLOGE("Cannot write to save persistent data");
645 goto err2;
646 }
647
648 /* Success */
649 free(pdata);
650 close(fd);
651 return 0;
652
653err2:
654 free(pdata);
655err:
656 close(fd);
657 return -1;
658}
659
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800660/* Convert a binary key of specified length into an ascii hex string equivalent,
661 * without the leading 0x and with null termination
662 */
663void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
664 char *master_key_ascii)
665{
666 unsigned int i, a;
667 unsigned char nibble;
668
669 for (i=0, a=0; i<keysize; i++, a+=2) {
670 /* For each byte, write out two ascii hex digits */
671 nibble = (master_key[i] >> 4) & 0xf;
672 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
673
674 nibble = master_key[i] & 0xf;
675 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
676 }
677
678 /* Add the null termination */
679 master_key_ascii[a] = '\0';
680
681}
682
Ken Sumralldb5e0262013-02-05 17:39:48 -0800683static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
684 char *real_blk_name, const char *name, int fd,
685 char *extra_params)
686{
687 char buffer[DM_CRYPT_BUF_SIZE];
688 struct dm_ioctl *io;
689 struct dm_target_spec *tgt;
690 char *crypt_params;
691 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
692 int i;
693
694 io = (struct dm_ioctl *) buffer;
695
696 /* Load the mapping table for this device */
697 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
698
699 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
700 io->target_count = 1;
701 tgt->status = 0;
702 tgt->sector_start = 0;
703 tgt->length = crypt_ftr->fs_size;
704 strcpy(tgt->target_type, "crypt");
705
706 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
707 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
708 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
709 master_key_ascii, real_blk_name, extra_params);
710 crypt_params += strlen(crypt_params) + 1;
711 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
712 tgt->next = crypt_params - buffer;
713
714 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
715 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
716 break;
717 }
718 usleep(500000);
719 }
720
721 if (i == TABLE_LOAD_RETRIES) {
722 /* We failed to load the table, return an error */
723 return -1;
724 } else {
725 return i + 1;
726 }
727}
728
729
730static int get_dm_crypt_version(int fd, const char *name, int *version)
731{
732 char buffer[DM_CRYPT_BUF_SIZE];
733 struct dm_ioctl *io;
734 struct dm_target_versions *v;
735 int i;
736
737 io = (struct dm_ioctl *) buffer;
738
739 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
740
741 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
742 return -1;
743 }
744
745 /* Iterate over the returned versions, looking for name of "crypt".
746 * When found, get and return the version.
747 */
748 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
749 while (v->next) {
750 if (! strcmp(v->name, "crypt")) {
751 /* We found the crypt driver, return the version, and get out */
752 version[0] = v->version[0];
753 version[1] = v->version[1];
754 version[2] = v->version[2];
755 return 0;
756 }
757 v = (struct dm_target_versions *)(((char *)v) + v->next);
758 }
759
760 return -1;
761}
762
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800763static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -0700764 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800765{
766 char buffer[DM_CRYPT_BUF_SIZE];
767 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
768 char *crypt_params;
769 struct dm_ioctl *io;
770 struct dm_target_spec *tgt;
771 unsigned int minor;
772 int fd;
Ken Sumralle919efe2012-09-29 17:07:41 -0700773 int i;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800774 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800775 int version[3];
776 char *extra_params;
777 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800778
779 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
780 SLOGE("Cannot open device-mapper\n");
781 goto errout;
782 }
783
784 io = (struct dm_ioctl *) buffer;
785
786 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
787 if (ioctl(fd, DM_DEV_CREATE, io)) {
788 SLOGE("Cannot create dm-crypt device\n");
789 goto errout;
790 }
791
792 /* Get the device status, in particular, the name of it's device file */
793 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
794 if (ioctl(fd, DM_DEV_STATUS, io)) {
795 SLOGE("Cannot retrieve dm-crypt device status\n");
796 goto errout;
797 }
798 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
799 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
800
Ken Sumralldb5e0262013-02-05 17:39:48 -0800801 extra_params = "";
802 if (! get_dm_crypt_version(fd, name, version)) {
803 /* Support for allow_discards was added in version 1.11.0 */
804 if ((version[0] >= 2) ||
805 ((version[0] == 1) && (version[1] >= 11))) {
806 extra_params = "1 allow_discards";
807 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
808 }
Ken Sumralle919efe2012-09-29 17:07:41 -0700809 }
810
Ken Sumralldb5e0262013-02-05 17:39:48 -0800811 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
812 fd, extra_params);
813 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800814 SLOGE("Cannot load dm-crypt mapping table.\n");
815 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800816 } else if (load_count > 1) {
817 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800818 }
819
820 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -0800821 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800822
823 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
824 SLOGE("Cannot resume the dm-crypt device\n");
825 goto errout;
826 }
827
828 /* We made it here with no errors. Woot! */
829 retval = 0;
830
831errout:
832 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
833
834 return retval;
835}
836
Ken Sumrall29d8da82011-05-18 17:20:07 -0700837static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800838{
839 int fd;
840 char buffer[DM_CRYPT_BUF_SIZE];
841 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800842 int retval = -1;
843
844 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
845 SLOGE("Cannot open device-mapper\n");
846 goto errout;
847 }
848
849 io = (struct dm_ioctl *) buffer;
850
851 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
852 if (ioctl(fd, DM_DEV_REMOVE, io)) {
853 SLOGE("Cannot remove dm-crypt device\n");
854 goto errout;
855 }
856
857 /* We made it here with no errors. Woot! */
858 retval = 0;
859
860errout:
861 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
862
863 return retval;
864
865}
866
Kenny Rootc4c70f12013-06-14 12:11:38 -0700867static void pbkdf2(char *passwd, unsigned char *salt, unsigned char *ikey, void *params) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800868 /* Turn the password into a key and IV that can decrypt the master key */
Ken Sumralle8744072011-01-18 22:01:55 -0800869 PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800870 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800871}
872
Kenny Rootc4c70f12013-06-14 12:11:38 -0700873static void scrypt(char *passwd, unsigned char *salt, unsigned char *ikey, void *params) {
874 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
875
876 int N = 1 << ftr->N_factor;
877 int r = 1 << ftr->r_factor;
878 int p = 1 << ftr->p_factor;
879
880 /* Turn the password into a key and IV that can decrypt the master key */
881 crypto_scrypt((unsigned char *) passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
882 KEY_LEN_BYTES + IV_LEN_BYTES);
883}
884
Ken Sumralle8744072011-01-18 22:01:55 -0800885static int encrypt_master_key(char *passwd, unsigned char *salt,
886 unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700887 unsigned char *encrypted_master_key,
888 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800889{
890 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
891 EVP_CIPHER_CTX e_ctx;
892 int encrypted_len, final_len;
893
894 /* Turn the password into a key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700895 get_device_scrypt_params(crypt_ftr);
896 scrypt(passwd, salt, ikey, crypt_ftr);
897
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800898 /* Initialize the decryption engine */
899 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
900 SLOGE("EVP_EncryptInit failed\n");
901 return -1;
902 }
903 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800904
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800905 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800906 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
907 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800908 SLOGE("EVP_EncryptUpdate failed\n");
909 return -1;
910 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800911 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800912 SLOGE("EVP_EncryptFinal failed\n");
913 return -1;
914 }
915
916 if (encrypted_len + final_len != KEY_LEN_BYTES) {
917 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
918 return -1;
919 } else {
920 return 0;
921 }
922}
923
Ken Sumralle8744072011-01-18 22:01:55 -0800924static int decrypt_master_key(char *passwd, unsigned char *salt,
925 unsigned char *encrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700926 unsigned char *decrypted_master_key,
927 kdf_func kdf, void *kdf_params)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800928{
929 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 -0800930 EVP_CIPHER_CTX d_ctx;
931 int decrypted_len, final_len;
932
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800933 /* Turn the password into a key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700934 kdf(passwd, salt, ikey, kdf_params);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800935
936 /* Initialize the decryption engine */
937 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
938 return -1;
939 }
940 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
941 /* Decrypt the master key */
942 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
943 encrypted_master_key, KEY_LEN_BYTES)) {
944 return -1;
945 }
946 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
947 return -1;
948 }
949
950 if (decrypted_len + final_len != KEY_LEN_BYTES) {
951 return -1;
952 } else {
953 return 0;
954 }
955}
956
Kenny Rootc4c70f12013-06-14 12:11:38 -0700957static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800958{
Kenny Rootc4c70f12013-06-14 12:11:38 -0700959 if (ftr->kdf_type == KDF_SCRYPT) {
960 *kdf = scrypt;
961 *kdf_params = ftr;
962 } else {
963 *kdf = pbkdf2;
964 *kdf_params = NULL;
965 }
966}
967
968static int decrypt_master_key_and_upgrade(char *passwd, unsigned char *decrypted_master_key,
969 struct crypt_mnt_ftr *crypt_ftr)
970{
971 kdf_func kdf;
972 void *kdf_params;
973 int ret;
974
975 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
976 ret = decrypt_master_key(passwd, crypt_ftr->salt, crypt_ftr->master_key, decrypted_master_key, kdf,
977 kdf_params);
978 if (ret != 0) {
979 SLOGW("failure decrypting master key");
980 return ret;
981 }
982
983 /*
984 * Upgrade if we're not using the latest KDF.
985 */
986 if (crypt_ftr->kdf_type != KDF_SCRYPT) {
987 crypt_ftr->kdf_type = KDF_SCRYPT;
988 encrypt_master_key(passwd, crypt_ftr->salt, decrypted_master_key, crypt_ftr->master_key,
989 crypt_ftr);
990 put_crypt_ftr_and_key(crypt_ftr);
991 }
992
993 return ret;
994}
995
996static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
997 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800998 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -0800999 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001000 EVP_CIPHER_CTX e_ctx;
1001 int encrypted_len, final_len;
1002
1003 /* Get some random bits for a key */
1004 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001005 read(fd, key_buf, sizeof(key_buf));
1006 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001007 close(fd);
1008
1009 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001010 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001011}
1012
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001013static int wait_and_unmount(char *mountpoint)
1014{
1015 int i, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001016#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001017
1018 /* Now umount the tmpfs filesystem */
1019 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
1020 if (umount(mountpoint)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001021 if (errno == EINVAL) {
1022 /* EINVAL is returned if the directory is not a mountpoint,
1023 * i.e. there is no filesystem mounted there. So just get out.
1024 */
1025 break;
1026 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001027 sleep(1);
1028 i++;
1029 } else {
1030 break;
1031 }
1032 }
1033
1034 if (i < WAIT_UNMOUNT_COUNT) {
1035 SLOGD("unmounting %s succeeded\n", mountpoint);
1036 rc = 0;
1037 } else {
1038 SLOGE("unmounting %s failed\n", mountpoint);
1039 rc = -1;
1040 }
1041
1042 return rc;
1043}
1044
Ken Sumrallc5872692013-05-14 15:26:31 -07001045#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001046static int prep_data_fs(void)
1047{
1048 int i;
1049
1050 /* Do the prep of the /data filesystem */
1051 property_set("vold.post_fs_data_done", "0");
1052 property_set("vold.decrypt", "trigger_post_fs_data");
1053 SLOGD("Just triggered post_fs_data\n");
1054
Ken Sumrallc5872692013-05-14 15:26:31 -07001055 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001056 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001057 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001058
1059 property_get("vold.post_fs_data_done", p, "0");
1060 if (*p == '1') {
1061 break;
1062 } else {
1063 usleep(250000);
1064 }
1065 }
1066 if (i == DATA_PREP_TIMEOUT) {
1067 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001068 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001069 return -1;
1070 } else {
1071 SLOGD("post_fs_data done\n");
1072 return 0;
1073 }
1074}
1075
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001076int cryptfs_restart(void)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001077{
1078 char fs_type[32];
1079 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001080 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001081 char fs_options[256];
1082 unsigned long mnt_flags;
1083 struct stat statbuf;
1084 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001085 static int restart_successful = 0;
1086
1087 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001088 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001089 SLOGE("Encrypted filesystem not validated, aborting");
1090 return -1;
1091 }
1092
1093 if (restart_successful) {
1094 SLOGE("System already restarted with encrypted disk, aborting");
1095 return -1;
1096 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001097
1098 /* Here is where we shut down the framework. The init scripts
1099 * start all services in one of three classes: core, main or late_start.
1100 * On boot, we start core and main. Now, we stop main, but not core,
1101 * as core includes vold and a few other really important things that
1102 * we need to keep running. Once main has stopped, we should be able
1103 * to umount the tmpfs /data, then mount the encrypted /data.
1104 * We then restart the class main, and also the class late_start.
1105 * At the moment, I've only put a few things in late_start that I know
1106 * are not needed to bring up the framework, and that also cause problems
1107 * with unmounting the tmpfs /data, but I hope to add add more services
1108 * to the late_start class as we optimize this to decrease the delay
1109 * till the user is asked for the password to the filesystem.
1110 */
1111
1112 /* The init files are setup to stop the class main when vold.decrypt is
1113 * set to trigger_reset_main.
1114 */
1115 property_set("vold.decrypt", "trigger_reset_main");
1116 SLOGD("Just asked init to shut down class main\n");
1117
Ken Sumrall92736ef2012-10-17 20:57:14 -07001118 /* Ugh, shutting down the framework is not synchronous, so until it
1119 * can be fixed, this horrible hack will wait a moment for it all to
1120 * shut down before proceeding. Without it, some devices cannot
1121 * restart the graphics services.
1122 */
1123 sleep(2);
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001124
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001125 /* Now that the framework is shutdown, we should be able to umount()
1126 * the tmpfs filesystem, and mount the real one.
1127 */
1128
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001129 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1130 if (strlen(crypto_blkdev) == 0) {
1131 SLOGE("fs_crypto_blkdev not set\n");
1132 return -1;
1133 }
1134
Ken Sumralle5032c42012-04-01 23:58:44 -07001135 if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
1136 /* If that succeeded, then mount the decrypted filesystem */
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001137 fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001138
Ken Sumralle5032c42012-04-01 23:58:44 -07001139 property_set("vold.decrypt", "trigger_load_persist_props");
1140 /* Create necessary paths on /data */
1141 if (prep_data_fs()) {
1142 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001143 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001144
1145 /* startup service classes main and late_start */
1146 property_set("vold.decrypt", "trigger_restart_framework");
1147 SLOGD("Just triggered restart_framework\n");
1148
1149 /* Give it a few moments to get started */
1150 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001151 }
1152
Ken Sumrall0cc16632011-01-18 20:32:26 -08001153 if (rc == 0) {
1154 restart_successful = 1;
1155 }
1156
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001157 return rc;
1158}
1159
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001160static int do_crypto_complete(char *mount_point)
1161{
1162 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001163 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001164 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001165
1166 property_get("ro.crypto.state", encrypted_state, "");
1167 if (strcmp(encrypted_state, "encrypted") ) {
1168 SLOGE("not running with encryption, aborting");
1169 return 1;
1170 }
1171
Ken Sumrall160b4d62013-04-22 12:15:39 -07001172 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001173 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001174
Ken Sumralle1a45852011-12-14 21:24:27 -08001175 /*
1176 * Only report this error if key_loc is a file and it exists.
1177 * If the device was never encrypted, and /data is not mountable for
1178 * some reason, returning 1 should prevent the UI from presenting the
1179 * a "enter password" screen, or worse, a "press button to wipe the
1180 * device" screen.
1181 */
1182 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1183 SLOGE("master key file does not exist, aborting");
1184 return 1;
1185 } else {
1186 SLOGE("Error getting crypt footer and key\n");
1187 return -1;
1188 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001189 }
1190
1191 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1192 SLOGE("Encryption process didn't finish successfully\n");
1193 return -2; /* -2 is the clue to the UI that there is no usable data on the disk,
1194 * and give the user an option to wipe the disk */
1195 }
1196
1197 /* We passed the test! We shall diminish, and return to the west */
1198 return 0;
1199}
1200
Ken Sumrall29d8da82011-05-18 17:20:07 -07001201static int test_mount_encrypted_fs(char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001202{
1203 struct crypt_mnt_ftr crypt_ftr;
1204 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001205 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001206 char crypto_blkdev[MAXPATHLEN];
1207 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001208 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001209 unsigned int orig_failed_decrypt_count;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001210 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001211 int rc;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001212 kdf_func kdf;
1213 void *kdf_params;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001214
Ken Sumrall0cc16632011-01-18 20:32:26 -08001215 property_get("ro.crypto.state", encrypted_state, "");
Jason parks70a4b3f2011-01-28 10:10:47 -06001216 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001217 SLOGE("encrypted fs already validated or not running with encryption, aborting");
1218 return -1;
1219 }
1220
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001221 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001222
Ken Sumrall160b4d62013-04-22 12:15:39 -07001223 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001224 SLOGE("Error getting crypt footer and key\n");
1225 return -1;
1226 }
Ken Sumralld33d4172011-02-01 00:49:13 -08001227
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001228 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr.fs_size);
1229 orig_failed_decrypt_count = crypt_ftr.failed_decrypt_count;
1230
1231 if (! (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001232 decrypt_master_key_and_upgrade(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001233 }
1234
1235 if (create_crypto_blk_dev(&crypt_ftr, decrypted_master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -07001236 real_blkdev, crypto_blkdev, label)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001237 SLOGE("Error creating decrypted block device\n");
1238 return -1;
1239 }
1240
Alex Klyubin707795a2013-05-10 15:17:07 -07001241 /* If init detects an encrypted filesystem, it writes a file for each such
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001242 * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
1243 * files and passes that data to me */
1244 /* Create a tmp mount point to try mounting the decryptd fs
1245 * Since we're here, the mount_point should be a tmpfs filesystem, so make
1246 * a directory in it to test mount the decrypted filesystem.
1247 */
1248 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1249 mkdir(tmp_mount_point, 0755);
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001250 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001251 SLOGE("Error temp mounting decrypted block device\n");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001252 delete_crypto_blk_dev(label);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001253 crypt_ftr.failed_decrypt_count++;
1254 } else {
1255 /* Success, so just umount and we'll mount it properly when we restart
1256 * the framework.
1257 */
1258 umount(tmp_mount_point);
1259 crypt_ftr.failed_decrypt_count = 0;
1260 }
1261
1262 if (orig_failed_decrypt_count != crypt_ftr.failed_decrypt_count) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001263 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001264 }
1265
1266 if (crypt_ftr.failed_decrypt_count) {
1267 /* We failed to mount the device, so return an error */
1268 rc = crypt_ftr.failed_decrypt_count;
1269
1270 } else {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001271 /* Woot! Success! Save the name of the crypto block device
1272 * so we can mount it when restarting the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001273 */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001274 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001275
1276 /* Also save a the master key so we can reencrypted the key
1277 * the key when we want to change the password on it.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001278 */
Jason parks70a4b3f2011-01-28 10:10:47 -06001279 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001280 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001281 master_key_saved = 1;
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001282 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001283 }
1284
1285 return rc;
1286}
1287
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001288/* Called by vold when it wants to undo the crypto mapping of a volume it
1289 * manages. This is usually in response to a factory reset, when we want
1290 * to undo the crypto mapping so the volume is formatted in the clear.
1291 */
1292int cryptfs_revert_volume(const char *label)
1293{
1294 return delete_crypto_blk_dev((char *)label);
1295}
1296
Ken Sumrall29d8da82011-05-18 17:20:07 -07001297/*
1298 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1299 * Setup a dm-crypt mapping, use the saved master key from
1300 * setting up the /data mapping, and return the new device path.
1301 */
1302int cryptfs_setup_volume(const char *label, int major, int minor,
1303 char *crypto_sys_path, unsigned int max_path,
1304 int *new_major, int *new_minor)
1305{
1306 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1307 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001308 struct stat statbuf;
1309 int nr_sec, fd;
1310
1311 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1312
Ken Sumrall160b4d62013-04-22 12:15:39 -07001313 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001314
1315 /* Update the fs_size field to be the size of the volume */
1316 fd = open(real_blkdev, O_RDONLY);
1317 nr_sec = get_blkdev_size(fd);
1318 close(fd);
1319 if (nr_sec == 0) {
1320 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1321 return -1;
1322 }
1323
1324 sd_crypt_ftr.fs_size = nr_sec;
1325 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1326 crypto_blkdev, label);
1327
1328 stat(crypto_blkdev, &statbuf);
1329 *new_major = MAJOR(statbuf.st_rdev);
1330 *new_minor = MINOR(statbuf.st_rdev);
1331
1332 /* Create path to sys entry for this block device */
1333 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1334
1335 return 0;
1336}
1337
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001338int cryptfs_crypto_complete(void)
1339{
1340 return do_crypto_complete("/data");
1341}
1342
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001343int cryptfs_check_passwd(char *passwd)
1344{
1345 int rc = -1;
1346
Ken Sumrall29d8da82011-05-18 17:20:07 -07001347 rc = test_mount_encrypted_fs(passwd, DATA_MNT_POINT, "userdata");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001348
1349 return rc;
1350}
1351
Ken Sumrall3ad90722011-10-04 20:38:29 -07001352int cryptfs_verify_passwd(char *passwd)
1353{
1354 struct crypt_mnt_ftr crypt_ftr;
1355 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001356 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001357 char encrypted_state[PROPERTY_VALUE_MAX];
1358 int rc;
1359
1360 property_get("ro.crypto.state", encrypted_state, "");
1361 if (strcmp(encrypted_state, "encrypted") ) {
1362 SLOGE("device not encrypted, aborting");
1363 return -2;
1364 }
1365
1366 if (!master_key_saved) {
1367 SLOGE("encrypted fs not yet mounted, aborting");
1368 return -1;
1369 }
1370
1371 if (!saved_mount_point) {
1372 SLOGE("encrypted fs failed to save mount point, aborting");
1373 return -1;
1374 }
1375
Ken Sumrall160b4d62013-04-22 12:15:39 -07001376 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001377 SLOGE("Error getting crypt footer and key\n");
1378 return -1;
1379 }
1380
1381 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1382 /* If the device has no password, then just say the password is valid */
1383 rc = 0;
1384 } else {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001385 decrypt_master_key_and_upgrade(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001386 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1387 /* They match, the password is correct */
1388 rc = 0;
1389 } else {
1390 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1391 sleep(1);
1392 rc = 1;
1393 }
1394 }
1395
1396 return rc;
1397}
1398
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001399/* Initialize a crypt_mnt_ftr structure. The keysize is
1400 * defaulted to 16 bytes, and the filesystem size to 0.
1401 * Presumably, at a minimum, the caller will update the
1402 * filesystem size and crypto_type_name after calling this function.
1403 */
1404static void cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
1405{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001406 off64_t off;
1407
1408 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001409 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001410 ftr->major_version = CURRENT_MAJOR_VERSION;
1411 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001412 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001413 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001414
Kenny Rootc4c70f12013-06-14 12:11:38 -07001415 ftr->kdf_type = KDF_SCRYPT;
1416 get_device_scrypt_params(ftr);
1417
Ken Sumrall160b4d62013-04-22 12:15:39 -07001418 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1419 if (get_crypt_ftr_info(NULL, &off) == 0) {
1420 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1421 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1422 ftr->persist_data_size;
1423 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001424}
1425
Ken Sumrall29d8da82011-05-18 17:20:07 -07001426static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001427{
1428 char cmdline[256];
1429 int rc = -1;
1430
Ken Sumrall29d8da82011-05-18 17:20:07 -07001431 if (type == EXT4_FS) {
1432 snprintf(cmdline, sizeof(cmdline), "/system/bin/make_ext4fs -a /data -l %lld %s",
1433 size * 512, crypto_blkdev);
1434 SLOGI("Making empty filesystem with command %s\n", cmdline);
1435 } else if (type== FAT_FS) {
1436 snprintf(cmdline, sizeof(cmdline), "/system/bin/newfs_msdos -F 32 -O android -c 8 -s %lld %s",
1437 size, crypto_blkdev);
1438 SLOGI("Making empty filesystem with command %s\n", cmdline);
1439 } else {
1440 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1441 return -1;
1442 }
1443
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001444 if (system(cmdline)) {
1445 SLOGE("Error creating empty filesystem on %s\n", crypto_blkdev);
1446 } else {
1447 SLOGD("Successfully created empty filesystem on %s\n", crypto_blkdev);
1448 rc = 0;
1449 }
1450
1451 return rc;
1452}
1453
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001454#define CRYPT_INPLACE_BUFSIZE 4096
1455#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / 512)
Ken Sumrall29d8da82011-05-18 17:20:07 -07001456static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev, off64_t size,
1457 off64_t *size_already_done, off64_t tot_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001458{
1459 int realfd, cryptofd;
1460 char *buf[CRYPT_INPLACE_BUFSIZE];
1461 int rc = -1;
1462 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001463 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001464 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001465
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001466 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
1467 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
1468 return -1;
1469 }
1470
1471 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
1472 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1473 close(realfd);
1474 return -1;
1475 }
1476
1477 /* This is pretty much a simple loop of reading 4K, and writing 4K.
1478 * The size passed in is the number of 512 byte sectors in the filesystem.
1479 * So compute the number of whole 4K blocks we should read/write,
1480 * and the remainder.
1481 */
1482 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
1483 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001484 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
1485 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001486
1487 SLOGE("Encrypting filesystem in place...");
1488
Ken Sumrall29d8da82011-05-18 17:20:07 -07001489 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001490 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001491 /* process the majority of the filesystem in blocks */
1492 for (i=0; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001493 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001494 if (new_pct > cur_pct) {
1495 char buf[8];
1496
1497 cur_pct = new_pct;
1498 snprintf(buf, sizeof(buf), "%lld", cur_pct);
1499 property_set("vold.encrypt_progress", buf);
1500 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001501 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1502 SLOGE("Error reading real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1503 goto errout;
1504 }
1505 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1506 SLOGE("Error writing crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1507 goto errout;
1508 }
1509 }
1510
1511 /* Do any remaining sectors */
1512 for (i=0; i<remainder; i++) {
1513 if (unix_read(realfd, buf, 512) <= 0) {
1514 SLOGE("Error reading rival sectors from real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1515 goto errout;
1516 }
1517 if (unix_write(cryptofd, buf, 512) <= 0) {
1518 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1519 goto errout;
1520 }
1521 }
1522
Ken Sumrall29d8da82011-05-18 17:20:07 -07001523 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001524 rc = 0;
1525
1526errout:
1527 close(realfd);
1528 close(cryptofd);
1529
1530 return rc;
1531}
1532
1533#define CRYPTO_ENABLE_WIPE 1
1534#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001535
1536#define FRAMEWORK_BOOT_WAIT 60
1537
Ken Sumrall29d8da82011-05-18 17:20:07 -07001538static inline int should_encrypt(struct volume_info *volume)
1539{
1540 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
1541 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
1542}
1543
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001544int cryptfs_enable(char *howarg, char *passwd)
1545{
1546 int how = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001547 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN], sd_crypto_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07001548 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001549 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07001550 int rc=-1, fd, i, ret;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001551 struct crypt_mnt_ftr crypt_ftr, sd_crypt_ftr;;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001552 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001553 char tmpfs_options[PROPERTY_VALUE_MAX];
1554 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001555 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07001556 char key_loc[PROPERTY_VALUE_MAX];
1557 char fuse_sdcard[PROPERTY_VALUE_MAX];
1558 char *sd_mnt_point;
1559 char sd_blk_dev[256] = { 0 };
1560 int num_vols;
1561 struct volume_info *vol_list = 0;
1562 off64_t cur_encryption_done=0, tot_encryption_size=0;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001563
1564 property_get("ro.crypto.state", encrypted_state, "");
1565 if (strcmp(encrypted_state, "unencrypted")) {
1566 SLOGE("Device is already running encrypted, aborting");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001567 goto error_unencrypted;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001568 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001569
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001570 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001571
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001572 if (!strcmp(howarg, "wipe")) {
1573 how = CRYPTO_ENABLE_WIPE;
1574 } else if (! strcmp(howarg, "inplace")) {
1575 how = CRYPTO_ENABLE_INPLACE;
1576 } else {
1577 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08001578 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001579 }
1580
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001581 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001582
Ken Sumrall3ed82362011-01-28 23:31:16 -08001583 /* Get the size of the real block device */
1584 fd = open(real_blkdev, O_RDONLY);
1585 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
1586 SLOGE("Cannot get size of block device %s\n", real_blkdev);
1587 goto error_unencrypted;
1588 }
1589 close(fd);
1590
1591 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001592 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001593 unsigned int fs_size_sec, max_fs_size_sec;
1594
1595 fs_size_sec = get_fs_size(real_blkdev);
1596 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1597
1598 if (fs_size_sec > max_fs_size_sec) {
1599 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
1600 goto error_unencrypted;
1601 }
1602 }
1603
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001604 /* Get a wakelock as this may take a while, and we don't want the
1605 * device to sleep on us. We'll grab a partial wakelock, and if the UI
1606 * wants to keep the screen on, it can grab a full wakelock.
1607 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001608 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001609 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
1610
Jeff Sharkey7382f812012-08-23 14:08:59 -07001611 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07001612 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07001613 if (!sd_mnt_point) {
1614 sd_mnt_point = getenv("EXTERNAL_STORAGE");
1615 }
1616 if (!sd_mnt_point) {
1617 sd_mnt_point = "/mnt/sdcard";
1618 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07001619
1620 num_vols=vold_getNumDirectVolumes();
1621 vol_list = malloc(sizeof(struct volume_info) * num_vols);
1622 vold_getDirectVolumeList(vol_list);
1623
1624 for (i=0; i<num_vols; i++) {
1625 if (should_encrypt(&vol_list[i])) {
1626 fd = open(vol_list[i].blk_dev, O_RDONLY);
1627 if ( (vol_list[i].size = get_blkdev_size(fd)) == 0) {
1628 SLOGE("Cannot get size of block device %s\n", vol_list[i].blk_dev);
1629 goto error_unencrypted;
1630 }
1631 close(fd);
1632
Ken Sumrall3b170052011-07-11 15:38:57 -07001633 ret=vold_disableVol(vol_list[i].label);
Ken Sumrall319b1042011-06-14 14:01:55 -07001634 if ((ret < 0) && (ret != UNMOUNT_NOT_MOUNTED_ERR)) {
1635 /* -2 is returned when the device exists but is not currently mounted.
1636 * ignore the error and continue. */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001637 SLOGE("Failed to unmount volume %s\n", vol_list[i].label);
1638 goto error_unencrypted;
1639 }
1640 }
1641 }
1642
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001643 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001644 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001645 */
1646 property_set("vold.decrypt", "trigger_shutdown_framework");
1647 SLOGD("Just asked init to shut down class main\n");
1648
Ken Sumrall425524d2012-06-14 20:55:28 -07001649 if (vold_unmountAllAsecs()) {
1650 /* Just report the error. If any are left mounted,
1651 * umounting /data below will fail and handle the error.
1652 */
1653 SLOGE("Error unmounting internal asecs");
1654 }
1655
Ken Sumrall29d8da82011-05-18 17:20:07 -07001656 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
1657 if (!strcmp(fuse_sdcard, "true")) {
1658 /* This is a device using the fuse layer to emulate the sdcard semantics
1659 * on top of the userdata partition. vold does not manage it, it is managed
1660 * by the sdcard service. The sdcard service was killed by the property trigger
1661 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
1662 * unlike the case for vold managed devices above.
1663 */
1664 if (wait_and_unmount(sd_mnt_point)) {
1665 goto error_shutting_down;
1666 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001667 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001668
1669 /* Now unmount the /data partition. */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001670 if (wait_and_unmount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001671 goto error_shutting_down;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001672 }
1673
1674 /* Do extra work for a better UX when doing the long inplace encryption */
1675 if (how == CRYPTO_ENABLE_INPLACE) {
1676 /* Now that /data is unmounted, we need to mount a tmpfs
1677 * /data, set a property saying we're doing inplace encryption,
1678 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001679 */
Ken Sumralle5032c42012-04-01 23:58:44 -07001680 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001681 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001682 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001683 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08001684 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001685
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001686 /* restart the framework. */
1687 /* Create necessary paths on /data */
1688 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001689 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001690 }
1691
Ken Sumrall92736ef2012-10-17 20:57:14 -07001692 /* Ugh, shutting down the framework is not synchronous, so until it
1693 * can be fixed, this horrible hack will wait a moment for it all to
1694 * shut down before proceeding. Without it, some devices cannot
1695 * restart the graphics services.
1696 */
1697 sleep(2);
1698
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001699 /* startup service classes main and late_start */
1700 property_set("vold.decrypt", "trigger_restart_min_framework");
1701 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001702
Ken Sumrall7df84122011-01-18 14:04:08 -08001703 /* OK, the framework is restarted and will soon be showing a
1704 * progress bar. Time to setup an encrypted mapping, and
1705 * either write a new filesystem, or encrypt in place updating
1706 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001707 */
1708 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001709
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001710 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001711 /* Initialize a crypt_mnt_ftr for the partition */
1712 cryptfs_init_crypt_mnt_ftr(&crypt_ftr);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001713
Ken Sumrall29d8da82011-05-18 17:20:07 -07001714 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
1715 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1716 } else {
1717 crypt_ftr.fs_size = nr_sec;
1718 }
Ken Sumralld33d4172011-02-01 00:49:13 -08001719 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001720 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
1721
1722 /* Make an encrypted master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001723 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001724 SLOGE("Cannot create encrypted master key\n");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001725 goto error_unencrypted;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001726 }
1727
1728 /* Write the key to the end of the partition */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001729 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001730
Ken Sumrall160b4d62013-04-22 12:15:39 -07001731 /* If any persistent data has been remembered, save it.
1732 * If none, create a valid empty table and save that.
1733 */
1734 if (!persist_data) {
1735 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
1736 if (pdata) {
1737 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
1738 persist_data = pdata;
1739 }
1740 }
1741 if (persist_data) {
1742 save_persistent_data();
1743 }
1744
Kenny Rootc4c70f12013-06-14 12:11:38 -07001745 decrypt_master_key_and_upgrade(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001746 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
1747 "userdata");
1748
Ken Sumrall128626f2011-06-28 18:45:14 -07001749 /* The size of the userdata partition, and add in the vold volumes below */
1750 tot_encryption_size = crypt_ftr.fs_size;
1751
Ken Sumrall29d8da82011-05-18 17:20:07 -07001752 /* setup crypto mapping for all encryptable volumes handled by vold */
1753 for (i=0; i<num_vols; i++) {
1754 if (should_encrypt(&vol_list[i])) {
1755 vol_list[i].crypt_ftr = crypt_ftr; /* gotta love struct assign */
1756 vol_list[i].crypt_ftr.fs_size = vol_list[i].size;
1757 create_crypto_blk_dev(&vol_list[i].crypt_ftr, decrypted_master_key,
1758 vol_list[i].blk_dev, vol_list[i].crypto_blkdev,
1759 vol_list[i].label);
Ken Sumrall128626f2011-06-28 18:45:14 -07001760 tot_encryption_size += vol_list[i].size;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001761 }
1762 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001763
1764 if (how == CRYPTO_ENABLE_WIPE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001765 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr.fs_size, EXT4_FS);
1766 /* Encrypt all encryptable volumes handled by vold */
1767 if (!rc) {
1768 for (i=0; i<num_vols; i++) {
1769 if (should_encrypt(&vol_list[i])) {
1770 rc = cryptfs_enable_wipe(vol_list[i].crypto_blkdev,
1771 vol_list[i].crypt_ftr.fs_size, FAT_FS);
1772 }
1773 }
1774 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001775 } else if (how == CRYPTO_ENABLE_INPLACE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001776 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr.fs_size,
1777 &cur_encryption_done, tot_encryption_size);
1778 /* Encrypt all encryptable volumes handled by vold */
1779 if (!rc) {
1780 for (i=0; i<num_vols; i++) {
1781 if (should_encrypt(&vol_list[i])) {
1782 rc = cryptfs_enable_inplace(vol_list[i].crypto_blkdev,
1783 vol_list[i].blk_dev,
1784 vol_list[i].crypt_ftr.fs_size,
1785 &cur_encryption_done, tot_encryption_size);
1786 }
1787 }
1788 }
1789 if (!rc) {
1790 /* The inplace routine never actually sets the progress to 100%
1791 * due to the round down nature of integer division, so set it here */
1792 property_set("vold.encrypt_progress", "100");
1793 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001794 } else {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001795 /* Shouldn't happen */
1796 SLOGE("cryptfs_enable: internal error, unknown option\n");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001797 goto error_unencrypted;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001798 }
1799
1800 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001801 delete_crypto_blk_dev("userdata");
1802 for (i=0; i<num_vols; i++) {
1803 if (should_encrypt(&vol_list[i])) {
1804 delete_crypto_blk_dev(vol_list[i].label);
1805 }
1806 }
1807
1808 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001809
1810 if (! rc) {
1811 /* Success */
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001812
Ken Sumralld33d4172011-02-01 00:49:13 -08001813 /* Clear the encryption in progres flag in the footer */
1814 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001815 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08001816
Ken Sumrall29d8da82011-05-18 17:20:07 -07001817 sleep(2); /* Give the UI a chance to show 100% progress */
Ken Sumralladfba362013-06-04 16:37:52 -07001818 cryptfs_reboot(0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001819 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001820 char value[PROPERTY_VALUE_MAX];
1821
Ken Sumrall319369a2012-06-27 16:30:18 -07001822 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001823 if (!strcmp(value, "1")) {
1824 /* wipe data if encryption failed */
1825 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
1826 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07001827 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001828 if (fd >= 0) {
1829 write(fd, "--wipe_data", strlen("--wipe_data") + 1);
1830 close(fd);
1831 } else {
1832 SLOGE("could not open /cache/recovery/command\n");
1833 }
Ken Sumralladfba362013-06-04 16:37:52 -07001834 cryptfs_reboot(1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001835 } else {
1836 /* set property to trigger dialog */
1837 property_set("vold.encrypt_progress", "error_partially_encrypted");
1838 release_wake_lock(lockid);
1839 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001840 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001841 }
1842
Ken Sumrall3ed82362011-01-28 23:31:16 -08001843 /* hrm, the encrypt step claims success, but the reboot failed.
1844 * This should not happen.
1845 * Set the property and return. Hope the framework can deal with it.
1846 */
1847 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001848 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001849 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08001850
1851error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07001852 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001853 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001854 if (lockid[0]) {
1855 release_wake_lock(lockid);
1856 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001857 return -1;
1858
1859error_shutting_down:
1860 /* we failed, and have not encrypted anthing, so the users's data is still intact,
1861 * but the framework is stopped and not restarted to show the error, so it's up to
1862 * vold to restart the system.
1863 */
1864 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Ken Sumralladfba362013-06-04 16:37:52 -07001865 cryptfs_reboot(0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001866
1867 /* shouldn't get here */
1868 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001869 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001870 if (lockid[0]) {
1871 release_wake_lock(lockid);
1872 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001873 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001874}
1875
Jason parks70a4b3f2011-01-28 10:10:47 -06001876int cryptfs_changepw(char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001877{
1878 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001879 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001880
1881 /* This is only allowed after we've successfully decrypted the master key */
Jason parks70a4b3f2011-01-28 10:10:47 -06001882 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001883 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001884 return -1;
1885 }
1886
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001887 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001888 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall57b63e62011-01-17 18:29:19 -08001889 SLOGE("Error getting crypt footer and key");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001890 return -1;
1891 }
1892
Kenny Rootc4c70f12013-06-14 12:11:38 -07001893 encrypt_master_key(newpw, crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001894
Jason parks70a4b3f2011-01-28 10:10:47 -06001895 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001896 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001897
1898 return 0;
1899}
Ken Sumrall160b4d62013-04-22 12:15:39 -07001900
1901static int persist_get_key(char *fieldname, char *value)
1902{
1903 unsigned int i;
1904
1905 if (persist_data == NULL) {
1906 return -1;
1907 }
1908 for (i = 0; i < persist_data->persist_valid_entries; i++) {
1909 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
1910 /* We found it! */
1911 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
1912 return 0;
1913 }
1914 }
1915
1916 return -1;
1917}
1918
1919static int persist_set_key(char *fieldname, char *value, int encrypted)
1920{
1921 unsigned int i;
1922 unsigned int num;
1923 struct crypt_mnt_ftr crypt_ftr;
1924 unsigned int max_persistent_entries;
1925 unsigned int dsize;
1926
1927 if (persist_data == NULL) {
1928 return -1;
1929 }
1930
1931 /* If encrypted, use the values from the crypt_ftr, otherwise
1932 * use the values for the current spec.
1933 */
1934 if (encrypted) {
1935 if(get_crypt_ftr_and_key(&crypt_ftr)) {
1936 return -1;
1937 }
1938 dsize = crypt_ftr.persist_data_size;
1939 } else {
1940 dsize = CRYPT_PERSIST_DATA_SIZE;
1941 }
1942 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
1943 sizeof(struct crypt_persist_entry);
1944
1945 num = persist_data->persist_valid_entries;
1946
1947 for (i = 0; i < num; i++) {
1948 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
1949 /* We found an existing entry, update it! */
1950 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
1951 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
1952 return 0;
1953 }
1954 }
1955
1956 /* We didn't find it, add it to the end, if there is room */
1957 if (persist_data->persist_valid_entries < max_persistent_entries) {
1958 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
1959 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
1960 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
1961 persist_data->persist_valid_entries++;
1962 return 0;
1963 }
1964
1965 return -1;
1966}
1967
1968/* Return the value of the specified field. */
1969int cryptfs_getfield(char *fieldname, char *value, int len)
1970{
1971 char temp_value[PROPERTY_VALUE_MAX];
1972 char real_blkdev[MAXPATHLEN];
1973 /* 0 is success, 1 is not encrypted,
1974 * -1 is value not set, -2 is any other error
1975 */
1976 int rc = -2;
1977
1978 if (persist_data == NULL) {
1979 load_persistent_data();
1980 if (persist_data == NULL) {
1981 SLOGE("Getfield error, cannot load persistent data");
1982 goto out;
1983 }
1984 }
1985
1986 if (!persist_get_key(fieldname, temp_value)) {
1987 /* We found it, copy it to the caller's buffer and return */
1988 strlcpy(value, temp_value, len);
1989 rc = 0;
1990 } else {
1991 /* Sadness, it's not there. Return the error */
1992 rc = -1;
1993 }
1994
1995out:
1996 return rc;
1997}
1998
1999/* Set the value of the specified field. */
2000int cryptfs_setfield(char *fieldname, char *value)
2001{
2002 struct crypt_persist_data stored_pdata;
2003 struct crypt_persist_data *pdata_p;
2004 struct crypt_mnt_ftr crypt_ftr;
2005 char encrypted_state[PROPERTY_VALUE_MAX];
2006 /* 0 is success, -1 is an error */
2007 int rc = -1;
2008 int encrypted = 0;
2009
2010 if (persist_data == NULL) {
2011 load_persistent_data();
2012 if (persist_data == NULL) {
2013 SLOGE("Setfield error, cannot load persistent data");
2014 goto out;
2015 }
2016 }
2017
2018 property_get("ro.crypto.state", encrypted_state, "");
2019 if (!strcmp(encrypted_state, "encrypted") ) {
2020 encrypted = 1;
2021 }
2022
2023 if (persist_set_key(fieldname, value, encrypted)) {
2024 goto out;
2025 }
2026
2027 /* If we are running encrypted, save the persistent data now */
2028 if (encrypted) {
2029 if (save_persistent_data()) {
2030 SLOGE("Setfield error, cannot save persistent data");
2031 goto out;
2032 }
2033 }
2034
2035 rc = 0;
2036
2037out:
2038 return rc;
2039}