blob: bad5d8a122cbcbcfa7561930a8746981c14500bf [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 Sumrallc290eaf2011-03-07 23:40:35 -080038#include <cutils/android_reboot.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"
Mike Lockwoodee6d8c42012-02-15 13:43:28 -080044#include "cutils/android_reboot.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080045#include "cutils/log.h"
46#include "cutils/properties.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080047#include "hardware_legacy/power.h"
Ken Sumrall29d8da82011-05-18 17:20:07 -070048#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070049#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070050#include "crypto_scrypt.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080051
52#define DM_CRYPT_BUF_SIZE 4096
Ken Sumrall8ddbe402011-01-17 15:26:29 -080053#define DATA_MNT_POINT "/data"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080054
Jason parks70a4b3f2011-01-28 10:10:47 -060055#define HASH_COUNT 2000
56#define KEY_LEN_BYTES 16
57#define IV_LEN_BYTES 16
58
Ken Sumrall29d8da82011-05-18 17:20:07 -070059#define KEY_IN_FOOTER "footer"
60
61#define EXT4_FS 1
62#define FAT_FS 2
63
Ken Sumralle919efe2012-09-29 17:07:41 -070064#define TABLE_LOAD_RETRIES 10
65
Ken Sumrall8f869aa2010-12-03 03:47:09 -080066char *me = "cryptfs";
67
Jason parks70a4b3f2011-01-28 10:10:47 -060068static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070069static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060070static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -070071static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -080072
73extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -080074
Ken Sumrall8f869aa2010-12-03 03:47:09 -080075static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
76{
77 memset(io, 0, dataSize);
78 io->data_size = dataSize;
79 io->data_start = sizeof(struct dm_ioctl);
80 io->version[0] = 4;
81 io->version[1] = 0;
82 io->version[2] = 0;
83 io->flags = flags;
84 if (name) {
85 strncpy(io->name, name, sizeof(io->name));
86 }
87}
88
Kenny Rootc4c70f12013-06-14 12:11:38 -070089/**
90 * Gets the default device scrypt parameters for key derivation time tuning.
91 * The parameters should lead to about one second derivation time for the
92 * given device.
93 */
94static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
95 const int default_params[] = SCRYPT_DEFAULTS;
96 int params[] = SCRYPT_DEFAULTS;
97 char paramstr[PROPERTY_VALUE_MAX];
98 char *token;
99 char *saveptr;
100 int i;
101
102 property_get(SCRYPT_PROP, paramstr, "");
103 if (paramstr[0] != '\0') {
104 /*
105 * The token we're looking for should be three integers separated by
106 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
107 */
108 for (token = strtok_r(paramstr, ":", &saveptr); token != NULL && i < 3;
109 i++, token = strtok_r(NULL, ":", &saveptr)) {
110 char *endptr;
111 params[i] = strtol(token, &endptr, 10);
112
113 /*
114 * Check that there was a valid number and it's 8-bit. If not,
115 * break out and the end check will take the default values.
116 */
117 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
118 break;
119 }
120 }
121
122 /*
123 * If there were not enough tokens or a token was malformed (not an
124 * integer), it will end up here and the default parameters can be
125 * taken.
126 */
127 if ((i != 3) || (token != NULL)) {
128 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
129 memcpy(params, default_params, sizeof(params));
130 }
131 }
132
133 ftr->N_factor = params[0];
134 ftr->r_factor = params[1];
135 ftr->p_factor = params[2];
136}
137
Ken Sumrall3ed82362011-01-28 23:31:16 -0800138static unsigned int get_fs_size(char *dev)
139{
140 int fd, block_size;
141 struct ext4_super_block sb;
142 off64_t len;
143
144 if ((fd = open(dev, O_RDONLY)) < 0) {
145 SLOGE("Cannot open device to get filesystem size ");
146 return 0;
147 }
148
149 if (lseek64(fd, 1024, SEEK_SET) < 0) {
150 SLOGE("Cannot seek to superblock");
151 return 0;
152 }
153
154 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
155 SLOGE("Cannot read superblock");
156 return 0;
157 }
158
159 close(fd);
160
161 block_size = 1024 << sb.s_log_block_size;
162 /* compute length in bytes */
163 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
164
165 /* return length in sectors */
166 return (unsigned int) (len / 512);
167}
168
Ken Sumrall160b4d62013-04-22 12:15:39 -0700169static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
170{
171 static int cached_data = 0;
172 static off64_t cached_off = 0;
173 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
174 int fd;
175 char key_loc[PROPERTY_VALUE_MAX];
176 char real_blkdev[PROPERTY_VALUE_MAX];
177 unsigned int nr_sec;
178 int rc = -1;
179
180 if (!cached_data) {
181 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
182
183 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
184 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
185 SLOGE("Cannot open real block device %s\n", real_blkdev);
186 return -1;
187 }
188
189 if ((nr_sec = get_blkdev_size(fd))) {
190 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
191 * encryption info footer and key, and plenty of bytes to spare for future
192 * growth.
193 */
194 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
195 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
196 cached_data = 1;
197 } else {
198 SLOGE("Cannot get size of block device %s\n", real_blkdev);
199 }
200 close(fd);
201 } else {
202 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
203 cached_off = 0;
204 cached_data = 1;
205 }
206 }
207
208 if (cached_data) {
209 if (metadata_fname) {
210 *metadata_fname = cached_metadata_fname;
211 }
212 if (off) {
213 *off = cached_off;
214 }
215 rc = 0;
216 }
217
218 return rc;
219}
220
Ken Sumralle8744072011-01-18 22:01:55 -0800221/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800222 * update the failed mount count but not change the key.
223 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700224static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800225{
226 int fd;
227 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700228 /* starting_off is set to the SEEK_SET offset
229 * where the crypto structure starts
230 */
231 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800232 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700233 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700234 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall3be890f2011-09-14 16:53:46 -0700235 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800236
Ken Sumrall160b4d62013-04-22 12:15:39 -0700237 if (get_crypt_ftr_info(&fname, &starting_off)) {
238 SLOGE("Unable to get crypt_ftr_info\n");
239 return -1;
240 }
241 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700242 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700243 return -1;
244 }
245 if ( (fd = open(fname, O_RDWR)) < 0) {
246 SLOGE("Cannot open footer file %s\n", fname);
247 return -1;
248 }
249
250 /* Seek to the start of the crypt footer */
251 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
252 SLOGE("Cannot seek to real block device footer\n");
253 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800254 }
255
256 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
257 SLOGE("Cannot write real block device footer\n");
258 goto errout;
259 }
260
Ken Sumrall3be890f2011-09-14 16:53:46 -0700261 fstat(fd, &statbuf);
262 /* If the keys are kept on a raw block device, do not try to truncate it. */
263 if (S_ISREG(statbuf.st_mode) && (key_loc[0] == '/')) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700264 if (ftruncate(fd, 0x4000)) {
Ken Sumrall3be890f2011-09-14 16:53:46 -0700265 SLOGE("Cannot set footer file size\n", fname);
Ken Sumralle8744072011-01-18 22:01:55 -0800266 goto errout;
267 }
268 }
269
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800270 /* Success! */
271 rc = 0;
272
273errout:
274 close(fd);
275 return rc;
276
277}
278
Ken Sumrall160b4d62013-04-22 12:15:39 -0700279static inline int unix_read(int fd, void* buff, int len)
280{
281 return TEMP_FAILURE_RETRY(read(fd, buff, len));
282}
283
284static inline int unix_write(int fd, const void* buff, int len)
285{
286 return TEMP_FAILURE_RETRY(write(fd, buff, len));
287}
288
289static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
290{
291 memset(pdata, 0, len);
292 pdata->persist_magic = PERSIST_DATA_MAGIC;
293 pdata->persist_valid_entries = 0;
294}
295
296/* A routine to update the passed in crypt_ftr to the lastest version.
297 * fd is open read/write on the device that holds the crypto footer and persistent
298 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
299 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
300 */
301static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
302{
Kenny Root7434b312013-06-14 11:29:53 -0700303 int orig_major = crypt_ftr->major_version;
304 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700305
Kenny Root7434b312013-06-14 11:29:53 -0700306 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
307 struct crypt_persist_data *pdata;
308 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700309
Kenny Rootc4c70f12013-06-14 12:11:38 -0700310 SLOGW("upgrading crypto footer to 1.1");
311
Kenny Root7434b312013-06-14 11:29:53 -0700312 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
313 if (pdata == NULL) {
314 SLOGE("Cannot allocate persisent data\n");
315 return;
316 }
317 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
318
319 /* Need to initialize the persistent data area */
320 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
321 SLOGE("Cannot seek to persisent data offset\n");
322 return;
323 }
324 /* Write all zeros to the first copy, making it invalid */
325 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
326
327 /* Write a valid but empty structure to the second copy */
328 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
329 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
330
331 /* Update the footer */
332 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
333 crypt_ftr->persist_data_offset[0] = pdata_offset;
334 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
335 crypt_ftr->minor_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700336 }
337
Kenny Rootc4c70f12013-06-14 12:11:38 -0700338 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version)) {
339 SLOGW("upgrading crypto footer to 1.2");
340 crypt_ftr->kdf_type = KDF_PBKDF2;
341 get_device_scrypt_params(crypt_ftr);
342 crypt_ftr->minor_version = 2;
343 }
344
Kenny Root7434b312013-06-14 11:29:53 -0700345 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
346 if (lseek64(fd, offset, SEEK_SET) == -1) {
347 SLOGE("Cannot seek to crypt footer\n");
348 return;
349 }
350 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700351 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700352}
353
354
355static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800356{
357 int fd;
358 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700359 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800360 int rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700361 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700362 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700363 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800364
Ken Sumrall160b4d62013-04-22 12:15:39 -0700365 if (get_crypt_ftr_info(&fname, &starting_off)) {
366 SLOGE("Unable to get crypt_ftr_info\n");
367 return -1;
368 }
369 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700370 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700371 return -1;
372 }
373 if ( (fd = open(fname, O_RDWR)) < 0) {
374 SLOGE("Cannot open footer file %s\n", fname);
375 return -1;
376 }
377
378 /* Make sure it's 16 Kbytes in length */
379 fstat(fd, &statbuf);
380 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
381 SLOGE("footer file %s is not the expected size!\n", fname);
382 goto errout;
383 }
384
385 /* Seek to the start of the crypt footer */
386 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
387 SLOGE("Cannot seek to real block device footer\n");
388 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800389 }
390
391 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
392 SLOGE("Cannot read real block device footer\n");
393 goto errout;
394 }
395
396 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700397 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800398 goto errout;
399 }
400
Kenny Rootc96a5f82013-06-14 12:08:28 -0700401 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
402 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
403 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800404 goto errout;
405 }
406
Kenny Rootc96a5f82013-06-14 12:08:28 -0700407 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
408 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
409 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800410 }
411
Ken Sumrall160b4d62013-04-22 12:15:39 -0700412 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
413 * copy on disk before returning.
414 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700415 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700416 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800417 }
418
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800419 /* Success! */
420 rc = 0;
421
422errout:
423 close(fd);
424 return rc;
425}
426
Ken Sumrall160b4d62013-04-22 12:15:39 -0700427static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
428{
429 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
430 crypt_ftr->persist_data_offset[1]) {
431 SLOGE("Crypt_ftr persist data regions overlap");
432 return -1;
433 }
434
435 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
436 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
437 return -1;
438 }
439
440 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
441 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
442 CRYPT_FOOTER_OFFSET) {
443 SLOGE("Persistent data extends past crypto footer");
444 return -1;
445 }
446
447 return 0;
448}
449
450static int load_persistent_data(void)
451{
452 struct crypt_mnt_ftr crypt_ftr;
453 struct crypt_persist_data *pdata = NULL;
454 char encrypted_state[PROPERTY_VALUE_MAX];
455 char *fname;
456 int found = 0;
457 int fd;
458 int ret;
459 int i;
460
461 if (persist_data) {
462 /* Nothing to do, we've already loaded or initialized it */
463 return 0;
464 }
465
466
467 /* If not encrypted, just allocate an empty table and initialize it */
468 property_get("ro.crypto.state", encrypted_state, "");
469 if (strcmp(encrypted_state, "encrypted") ) {
470 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
471 if (pdata) {
472 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
473 persist_data = pdata;
474 return 0;
475 }
476 return -1;
477 }
478
479 if(get_crypt_ftr_and_key(&crypt_ftr)) {
480 return -1;
481 }
482
483 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
484 SLOGE("Crypt_ftr version doesn't support persistent data");
485 return -1;
486 }
487
488 if (get_crypt_ftr_info(&fname, NULL)) {
489 return -1;
490 }
491
492 ret = validate_persistent_data_storage(&crypt_ftr);
493 if (ret) {
494 return -1;
495 }
496
497 fd = open(fname, O_RDONLY);
498 if (fd < 0) {
499 SLOGE("Cannot open %s metadata file", fname);
500 return -1;
501 }
502
503 if (persist_data == NULL) {
504 pdata = malloc(crypt_ftr.persist_data_size);
505 if (pdata == NULL) {
506 SLOGE("Cannot allocate memory for persistent data");
507 goto err;
508 }
509 }
510
511 for (i = 0; i < 2; i++) {
512 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
513 SLOGE("Cannot seek to read persistent data on %s", fname);
514 goto err2;
515 }
516 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
517 SLOGE("Error reading persistent data on iteration %d", i);
518 goto err2;
519 }
520 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
521 found = 1;
522 break;
523 }
524 }
525
526 if (!found) {
527 SLOGI("Could not find valid persistent data, creating");
528 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
529 }
530
531 /* Success */
532 persist_data = pdata;
533 close(fd);
534 return 0;
535
536err2:
537 free(pdata);
538
539err:
540 close(fd);
541 return -1;
542}
543
544static int save_persistent_data(void)
545{
546 struct crypt_mnt_ftr crypt_ftr;
547 struct crypt_persist_data *pdata;
548 char *fname;
549 off64_t write_offset;
550 off64_t erase_offset;
551 int found = 0;
552 int fd;
553 int ret;
554
555 if (persist_data == NULL) {
556 SLOGE("No persistent data to save");
557 return -1;
558 }
559
560 if(get_crypt_ftr_and_key(&crypt_ftr)) {
561 return -1;
562 }
563
564 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
565 SLOGE("Crypt_ftr version doesn't support persistent data");
566 return -1;
567 }
568
569 ret = validate_persistent_data_storage(&crypt_ftr);
570 if (ret) {
571 return -1;
572 }
573
574 if (get_crypt_ftr_info(&fname, NULL)) {
575 return -1;
576 }
577
578 fd = open(fname, O_RDWR);
579 if (fd < 0) {
580 SLOGE("Cannot open %s metadata file", fname);
581 return -1;
582 }
583
584 pdata = malloc(crypt_ftr.persist_data_size);
585 if (pdata == NULL) {
586 SLOGE("Cannot allocate persistant data");
587 goto err;
588 }
589
590 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
591 SLOGE("Cannot seek to read persistent data on %s", fname);
592 goto err2;
593 }
594
595 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
596 SLOGE("Error reading persistent data before save");
597 goto err2;
598 }
599
600 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
601 /* The first copy is the curent valid copy, so write to
602 * the second copy and erase this one */
603 write_offset = crypt_ftr.persist_data_offset[1];
604 erase_offset = crypt_ftr.persist_data_offset[0];
605 } else {
606 /* The second copy must be the valid copy, so write to
607 * the first copy, and erase the second */
608 write_offset = crypt_ftr.persist_data_offset[0];
609 erase_offset = crypt_ftr.persist_data_offset[1];
610 }
611
612 /* Write the new copy first, if successful, then erase the old copy */
613 if (lseek(fd, write_offset, SEEK_SET) < 0) {
614 SLOGE("Cannot seek to write persistent data");
615 goto err2;
616 }
617 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
618 (int) crypt_ftr.persist_data_size) {
619 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
620 SLOGE("Cannot seek to erase previous persistent data");
621 goto err2;
622 }
623 fsync(fd);
624 memset(pdata, 0, crypt_ftr.persist_data_size);
625 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
626 (int) crypt_ftr.persist_data_size) {
627 SLOGE("Cannot write to erase previous persistent data");
628 goto err2;
629 }
630 fsync(fd);
631 } else {
632 SLOGE("Cannot write to save persistent data");
633 goto err2;
634 }
635
636 /* Success */
637 free(pdata);
638 close(fd);
639 return 0;
640
641err2:
642 free(pdata);
643err:
644 close(fd);
645 return -1;
646}
647
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800648/* Convert a binary key of specified length into an ascii hex string equivalent,
649 * without the leading 0x and with null termination
650 */
651void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
652 char *master_key_ascii)
653{
654 unsigned int i, a;
655 unsigned char nibble;
656
657 for (i=0, a=0; i<keysize; i++, a+=2) {
658 /* For each byte, write out two ascii hex digits */
659 nibble = (master_key[i] >> 4) & 0xf;
660 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
661
662 nibble = master_key[i] & 0xf;
663 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
664 }
665
666 /* Add the null termination */
667 master_key_ascii[a] = '\0';
668
669}
670
Ken Sumralldb5e0262013-02-05 17:39:48 -0800671static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
672 char *real_blk_name, const char *name, int fd,
673 char *extra_params)
674{
675 char buffer[DM_CRYPT_BUF_SIZE];
676 struct dm_ioctl *io;
677 struct dm_target_spec *tgt;
678 char *crypt_params;
679 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
680 int i;
681
682 io = (struct dm_ioctl *) buffer;
683
684 /* Load the mapping table for this device */
685 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
686
687 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
688 io->target_count = 1;
689 tgt->status = 0;
690 tgt->sector_start = 0;
691 tgt->length = crypt_ftr->fs_size;
692 strcpy(tgt->target_type, "crypt");
693
694 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
695 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
696 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
697 master_key_ascii, real_blk_name, extra_params);
698 crypt_params += strlen(crypt_params) + 1;
699 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
700 tgt->next = crypt_params - buffer;
701
702 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
703 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
704 break;
705 }
706 usleep(500000);
707 }
708
709 if (i == TABLE_LOAD_RETRIES) {
710 /* We failed to load the table, return an error */
711 return -1;
712 } else {
713 return i + 1;
714 }
715}
716
717
718static int get_dm_crypt_version(int fd, const char *name, int *version)
719{
720 char buffer[DM_CRYPT_BUF_SIZE];
721 struct dm_ioctl *io;
722 struct dm_target_versions *v;
723 int i;
724
725 io = (struct dm_ioctl *) buffer;
726
727 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
728
729 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
730 return -1;
731 }
732
733 /* Iterate over the returned versions, looking for name of "crypt".
734 * When found, get and return the version.
735 */
736 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
737 while (v->next) {
738 if (! strcmp(v->name, "crypt")) {
739 /* We found the crypt driver, return the version, and get out */
740 version[0] = v->version[0];
741 version[1] = v->version[1];
742 version[2] = v->version[2];
743 return 0;
744 }
745 v = (struct dm_target_versions *)(((char *)v) + v->next);
746 }
747
748 return -1;
749}
750
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800751static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -0700752 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800753{
754 char buffer[DM_CRYPT_BUF_SIZE];
755 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
756 char *crypt_params;
757 struct dm_ioctl *io;
758 struct dm_target_spec *tgt;
759 unsigned int minor;
760 int fd;
Ken Sumralle919efe2012-09-29 17:07:41 -0700761 int i;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800762 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800763 int version[3];
764 char *extra_params;
765 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800766
767 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
768 SLOGE("Cannot open device-mapper\n");
769 goto errout;
770 }
771
772 io = (struct dm_ioctl *) buffer;
773
774 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
775 if (ioctl(fd, DM_DEV_CREATE, io)) {
776 SLOGE("Cannot create dm-crypt device\n");
777 goto errout;
778 }
779
780 /* Get the device status, in particular, the name of it's device file */
781 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
782 if (ioctl(fd, DM_DEV_STATUS, io)) {
783 SLOGE("Cannot retrieve dm-crypt device status\n");
784 goto errout;
785 }
786 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
787 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
788
Ken Sumralldb5e0262013-02-05 17:39:48 -0800789 extra_params = "";
790 if (! get_dm_crypt_version(fd, name, version)) {
791 /* Support for allow_discards was added in version 1.11.0 */
792 if ((version[0] >= 2) ||
793 ((version[0] == 1) && (version[1] >= 11))) {
794 extra_params = "1 allow_discards";
795 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
796 }
Ken Sumralle919efe2012-09-29 17:07:41 -0700797 }
798
Ken Sumralldb5e0262013-02-05 17:39:48 -0800799 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
800 fd, extra_params);
801 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800802 SLOGE("Cannot load dm-crypt mapping table.\n");
803 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800804 } else if (load_count > 1) {
805 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800806 }
807
808 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -0800809 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800810
811 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
812 SLOGE("Cannot resume the dm-crypt device\n");
813 goto errout;
814 }
815
816 /* We made it here with no errors. Woot! */
817 retval = 0;
818
819errout:
820 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
821
822 return retval;
823}
824
Ken Sumrall29d8da82011-05-18 17:20:07 -0700825static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800826{
827 int fd;
828 char buffer[DM_CRYPT_BUF_SIZE];
829 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800830 int retval = -1;
831
832 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
833 SLOGE("Cannot open device-mapper\n");
834 goto errout;
835 }
836
837 io = (struct dm_ioctl *) buffer;
838
839 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
840 if (ioctl(fd, DM_DEV_REMOVE, io)) {
841 SLOGE("Cannot remove dm-crypt device\n");
842 goto errout;
843 }
844
845 /* We made it here with no errors. Woot! */
846 retval = 0;
847
848errout:
849 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
850
851 return retval;
852
853}
854
Kenny Rootc4c70f12013-06-14 12:11:38 -0700855static void pbkdf2(char *passwd, unsigned char *salt, unsigned char *ikey, void *params) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800856 /* Turn the password into a key and IV that can decrypt the master key */
Ken Sumralle8744072011-01-18 22:01:55 -0800857 PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800858 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800859}
860
Kenny Rootc4c70f12013-06-14 12:11:38 -0700861static void scrypt(char *passwd, unsigned char *salt, unsigned char *ikey, void *params) {
862 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
863
864 int N = 1 << ftr->N_factor;
865 int r = 1 << ftr->r_factor;
866 int p = 1 << ftr->p_factor;
867
868 /* Turn the password into a key and IV that can decrypt the master key */
869 crypto_scrypt((unsigned char *) passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
870 KEY_LEN_BYTES + IV_LEN_BYTES);
871}
872
Ken Sumralle8744072011-01-18 22:01:55 -0800873static int encrypt_master_key(char *passwd, unsigned char *salt,
874 unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700875 unsigned char *encrypted_master_key,
876 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800877{
878 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
879 EVP_CIPHER_CTX e_ctx;
880 int encrypted_len, final_len;
881
882 /* Turn the password into a key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700883 get_device_scrypt_params(crypt_ftr);
884 scrypt(passwd, salt, ikey, crypt_ftr);
885
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800886 /* Initialize the decryption engine */
887 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
888 SLOGE("EVP_EncryptInit failed\n");
889 return -1;
890 }
891 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800892
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800893 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800894 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
895 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800896 SLOGE("EVP_EncryptUpdate failed\n");
897 return -1;
898 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800899 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800900 SLOGE("EVP_EncryptFinal failed\n");
901 return -1;
902 }
903
904 if (encrypted_len + final_len != KEY_LEN_BYTES) {
905 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
906 return -1;
907 } else {
908 return 0;
909 }
910}
911
Ken Sumralle8744072011-01-18 22:01:55 -0800912static int decrypt_master_key(char *passwd, unsigned char *salt,
913 unsigned char *encrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700914 unsigned char *decrypted_master_key,
915 kdf_func kdf, void *kdf_params)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800916{
917 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 -0800918 EVP_CIPHER_CTX d_ctx;
919 int decrypted_len, final_len;
920
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800921 /* Turn the password into a key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700922 kdf(passwd, salt, ikey, kdf_params);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800923
924 /* Initialize the decryption engine */
925 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
926 return -1;
927 }
928 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
929 /* Decrypt the master key */
930 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
931 encrypted_master_key, KEY_LEN_BYTES)) {
932 return -1;
933 }
934 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
935 return -1;
936 }
937
938 if (decrypted_len + final_len != KEY_LEN_BYTES) {
939 return -1;
940 } else {
941 return 0;
942 }
943}
944
Kenny Rootc4c70f12013-06-14 12:11:38 -0700945static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800946{
Kenny Rootc4c70f12013-06-14 12:11:38 -0700947 if (ftr->kdf_type == KDF_SCRYPT) {
948 *kdf = scrypt;
949 *kdf_params = ftr;
950 } else {
951 *kdf = pbkdf2;
952 *kdf_params = NULL;
953 }
954}
955
956static int decrypt_master_key_and_upgrade(char *passwd, unsigned char *decrypted_master_key,
957 struct crypt_mnt_ftr *crypt_ftr)
958{
959 kdf_func kdf;
960 void *kdf_params;
961 int ret;
962
963 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
964 ret = decrypt_master_key(passwd, crypt_ftr->salt, crypt_ftr->master_key, decrypted_master_key, kdf,
965 kdf_params);
966 if (ret != 0) {
967 SLOGW("failure decrypting master key");
968 return ret;
969 }
970
971 /*
972 * Upgrade if we're not using the latest KDF.
973 */
974 if (crypt_ftr->kdf_type != KDF_SCRYPT) {
975 crypt_ftr->kdf_type = KDF_SCRYPT;
976 encrypt_master_key(passwd, crypt_ftr->salt, decrypted_master_key, crypt_ftr->master_key,
977 crypt_ftr);
978 put_crypt_ftr_and_key(crypt_ftr);
979 }
980
981 return ret;
982}
983
984static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
985 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800986 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -0800987 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800988 EVP_CIPHER_CTX e_ctx;
989 int encrypted_len, final_len;
990
991 /* Get some random bits for a key */
992 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -0800993 read(fd, key_buf, sizeof(key_buf));
994 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800995 close(fd);
996
997 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700998 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800999}
1000
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001001static int wait_and_unmount(char *mountpoint)
1002{
1003 int i, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001004#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001005
1006 /* Now umount the tmpfs filesystem */
1007 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
1008 if (umount(mountpoint)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001009 if (errno == EINVAL) {
1010 /* EINVAL is returned if the directory is not a mountpoint,
1011 * i.e. there is no filesystem mounted there. So just get out.
1012 */
1013 break;
1014 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001015 sleep(1);
1016 i++;
1017 } else {
1018 break;
1019 }
1020 }
1021
1022 if (i < WAIT_UNMOUNT_COUNT) {
1023 SLOGD("unmounting %s succeeded\n", mountpoint);
1024 rc = 0;
1025 } else {
1026 SLOGE("unmounting %s failed\n", mountpoint);
1027 rc = -1;
1028 }
1029
1030 return rc;
1031}
1032
Ken Sumrallc5872692013-05-14 15:26:31 -07001033#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001034static int prep_data_fs(void)
1035{
1036 int i;
1037
1038 /* Do the prep of the /data filesystem */
1039 property_set("vold.post_fs_data_done", "0");
1040 property_set("vold.decrypt", "trigger_post_fs_data");
1041 SLOGD("Just triggered post_fs_data\n");
1042
Ken Sumrallc5872692013-05-14 15:26:31 -07001043 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001044 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001045 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001046
1047 property_get("vold.post_fs_data_done", p, "0");
1048 if (*p == '1') {
1049 break;
1050 } else {
1051 usleep(250000);
1052 }
1053 }
1054 if (i == DATA_PREP_TIMEOUT) {
1055 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001056 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001057 return -1;
1058 } else {
1059 SLOGD("post_fs_data done\n");
1060 return 0;
1061 }
1062}
1063
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001064int cryptfs_restart(void)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001065{
1066 char fs_type[32];
1067 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001068 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001069 char fs_options[256];
1070 unsigned long mnt_flags;
1071 struct stat statbuf;
1072 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001073 static int restart_successful = 0;
1074
1075 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001076 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001077 SLOGE("Encrypted filesystem not validated, aborting");
1078 return -1;
1079 }
1080
1081 if (restart_successful) {
1082 SLOGE("System already restarted with encrypted disk, aborting");
1083 return -1;
1084 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001085
1086 /* Here is where we shut down the framework. The init scripts
1087 * start all services in one of three classes: core, main or late_start.
1088 * On boot, we start core and main. Now, we stop main, but not core,
1089 * as core includes vold and a few other really important things that
1090 * we need to keep running. Once main has stopped, we should be able
1091 * to umount the tmpfs /data, then mount the encrypted /data.
1092 * We then restart the class main, and also the class late_start.
1093 * At the moment, I've only put a few things in late_start that I know
1094 * are not needed to bring up the framework, and that also cause problems
1095 * with unmounting the tmpfs /data, but I hope to add add more services
1096 * to the late_start class as we optimize this to decrease the delay
1097 * till the user is asked for the password to the filesystem.
1098 */
1099
1100 /* The init files are setup to stop the class main when vold.decrypt is
1101 * set to trigger_reset_main.
1102 */
1103 property_set("vold.decrypt", "trigger_reset_main");
1104 SLOGD("Just asked init to shut down class main\n");
1105
Ken Sumrall92736ef2012-10-17 20:57:14 -07001106 /* Ugh, shutting down the framework is not synchronous, so until it
1107 * can be fixed, this horrible hack will wait a moment for it all to
1108 * shut down before proceeding. Without it, some devices cannot
1109 * restart the graphics services.
1110 */
1111 sleep(2);
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001112
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001113 /* Now that the framework is shutdown, we should be able to umount()
1114 * the tmpfs filesystem, and mount the real one.
1115 */
1116
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001117 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1118 if (strlen(crypto_blkdev) == 0) {
1119 SLOGE("fs_crypto_blkdev not set\n");
1120 return -1;
1121 }
1122
Ken Sumralle5032c42012-04-01 23:58:44 -07001123 if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
1124 /* If that succeeded, then mount the decrypted filesystem */
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001125 fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001126
Ken Sumralle5032c42012-04-01 23:58:44 -07001127 property_set("vold.decrypt", "trigger_load_persist_props");
1128 /* Create necessary paths on /data */
1129 if (prep_data_fs()) {
1130 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001131 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001132
1133 /* startup service classes main and late_start */
1134 property_set("vold.decrypt", "trigger_restart_framework");
1135 SLOGD("Just triggered restart_framework\n");
1136
1137 /* Give it a few moments to get started */
1138 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001139 }
1140
Ken Sumrall0cc16632011-01-18 20:32:26 -08001141 if (rc == 0) {
1142 restart_successful = 1;
1143 }
1144
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001145 return rc;
1146}
1147
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001148static int do_crypto_complete(char *mount_point)
1149{
1150 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001151 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001152 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001153
1154 property_get("ro.crypto.state", encrypted_state, "");
1155 if (strcmp(encrypted_state, "encrypted") ) {
1156 SLOGE("not running with encryption, aborting");
1157 return 1;
1158 }
1159
Ken Sumrall160b4d62013-04-22 12:15:39 -07001160 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001161 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001162
Ken Sumralle1a45852011-12-14 21:24:27 -08001163 /*
1164 * Only report this error if key_loc is a file and it exists.
1165 * If the device was never encrypted, and /data is not mountable for
1166 * some reason, returning 1 should prevent the UI from presenting the
1167 * a "enter password" screen, or worse, a "press button to wipe the
1168 * device" screen.
1169 */
1170 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1171 SLOGE("master key file does not exist, aborting");
1172 return 1;
1173 } else {
1174 SLOGE("Error getting crypt footer and key\n");
1175 return -1;
1176 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001177 }
1178
1179 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1180 SLOGE("Encryption process didn't finish successfully\n");
1181 return -2; /* -2 is the clue to the UI that there is no usable data on the disk,
1182 * and give the user an option to wipe the disk */
1183 }
1184
1185 /* We passed the test! We shall diminish, and return to the west */
1186 return 0;
1187}
1188
Ken Sumrall29d8da82011-05-18 17:20:07 -07001189static int test_mount_encrypted_fs(char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001190{
1191 struct crypt_mnt_ftr crypt_ftr;
1192 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001193 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001194 char crypto_blkdev[MAXPATHLEN];
1195 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001196 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001197 unsigned int orig_failed_decrypt_count;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001198 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001199 int rc;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001200 kdf_func kdf;
1201 void *kdf_params;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001202
Ken Sumrall0cc16632011-01-18 20:32:26 -08001203 property_get("ro.crypto.state", encrypted_state, "");
Jason parks70a4b3f2011-01-28 10:10:47 -06001204 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001205 SLOGE("encrypted fs already validated or not running with encryption, aborting");
1206 return -1;
1207 }
1208
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001209 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001210
Ken Sumrall160b4d62013-04-22 12:15:39 -07001211 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001212 SLOGE("Error getting crypt footer and key\n");
1213 return -1;
1214 }
Ken Sumralld33d4172011-02-01 00:49:13 -08001215
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001216 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr.fs_size);
1217 orig_failed_decrypt_count = crypt_ftr.failed_decrypt_count;
1218
1219 if (! (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001220 decrypt_master_key_and_upgrade(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001221 }
1222
1223 if (create_crypto_blk_dev(&crypt_ftr, decrypted_master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -07001224 real_blkdev, crypto_blkdev, label)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001225 SLOGE("Error creating decrypted block device\n");
1226 return -1;
1227 }
1228
Alex Klyubin707795a2013-05-10 15:17:07 -07001229 /* If init detects an encrypted filesystem, it writes a file for each such
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001230 * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
1231 * files and passes that data to me */
1232 /* Create a tmp mount point to try mounting the decryptd fs
1233 * Since we're here, the mount_point should be a tmpfs filesystem, so make
1234 * a directory in it to test mount the decrypted filesystem.
1235 */
1236 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1237 mkdir(tmp_mount_point, 0755);
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001238 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001239 SLOGE("Error temp mounting decrypted block device\n");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001240 delete_crypto_blk_dev(label);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001241 crypt_ftr.failed_decrypt_count++;
1242 } else {
1243 /* Success, so just umount and we'll mount it properly when we restart
1244 * the framework.
1245 */
1246 umount(tmp_mount_point);
1247 crypt_ftr.failed_decrypt_count = 0;
1248 }
1249
1250 if (orig_failed_decrypt_count != crypt_ftr.failed_decrypt_count) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001251 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001252 }
1253
1254 if (crypt_ftr.failed_decrypt_count) {
1255 /* We failed to mount the device, so return an error */
1256 rc = crypt_ftr.failed_decrypt_count;
1257
1258 } else {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001259 /* Woot! Success! Save the name of the crypto block device
1260 * so we can mount it when restarting the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001261 */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001262 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001263
1264 /* Also save a the master key so we can reencrypted the key
1265 * the key when we want to change the password on it.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001266 */
Jason parks70a4b3f2011-01-28 10:10:47 -06001267 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001268 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001269 master_key_saved = 1;
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001270 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001271 }
1272
1273 return rc;
1274}
1275
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001276/* Called by vold when it wants to undo the crypto mapping of a volume it
1277 * manages. This is usually in response to a factory reset, when we want
1278 * to undo the crypto mapping so the volume is formatted in the clear.
1279 */
1280int cryptfs_revert_volume(const char *label)
1281{
1282 return delete_crypto_blk_dev((char *)label);
1283}
1284
Ken Sumrall29d8da82011-05-18 17:20:07 -07001285/*
1286 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1287 * Setup a dm-crypt mapping, use the saved master key from
1288 * setting up the /data mapping, and return the new device path.
1289 */
1290int cryptfs_setup_volume(const char *label, int major, int minor,
1291 char *crypto_sys_path, unsigned int max_path,
1292 int *new_major, int *new_minor)
1293{
1294 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1295 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001296 struct stat statbuf;
1297 int nr_sec, fd;
1298
1299 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1300
Ken Sumrall160b4d62013-04-22 12:15:39 -07001301 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001302
1303 /* Update the fs_size field to be the size of the volume */
1304 fd = open(real_blkdev, O_RDONLY);
1305 nr_sec = get_blkdev_size(fd);
1306 close(fd);
1307 if (nr_sec == 0) {
1308 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1309 return -1;
1310 }
1311
1312 sd_crypt_ftr.fs_size = nr_sec;
1313 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1314 crypto_blkdev, label);
1315
1316 stat(crypto_blkdev, &statbuf);
1317 *new_major = MAJOR(statbuf.st_rdev);
1318 *new_minor = MINOR(statbuf.st_rdev);
1319
1320 /* Create path to sys entry for this block device */
1321 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1322
1323 return 0;
1324}
1325
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001326int cryptfs_crypto_complete(void)
1327{
1328 return do_crypto_complete("/data");
1329}
1330
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001331int cryptfs_check_passwd(char *passwd)
1332{
1333 int rc = -1;
1334
Ken Sumrall29d8da82011-05-18 17:20:07 -07001335 rc = test_mount_encrypted_fs(passwd, DATA_MNT_POINT, "userdata");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001336
1337 return rc;
1338}
1339
Ken Sumrall3ad90722011-10-04 20:38:29 -07001340int cryptfs_verify_passwd(char *passwd)
1341{
1342 struct crypt_mnt_ftr crypt_ftr;
1343 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001344 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001345 char encrypted_state[PROPERTY_VALUE_MAX];
1346 int rc;
1347
1348 property_get("ro.crypto.state", encrypted_state, "");
1349 if (strcmp(encrypted_state, "encrypted") ) {
1350 SLOGE("device not encrypted, aborting");
1351 return -2;
1352 }
1353
1354 if (!master_key_saved) {
1355 SLOGE("encrypted fs not yet mounted, aborting");
1356 return -1;
1357 }
1358
1359 if (!saved_mount_point) {
1360 SLOGE("encrypted fs failed to save mount point, aborting");
1361 return -1;
1362 }
1363
Ken Sumrall160b4d62013-04-22 12:15:39 -07001364 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001365 SLOGE("Error getting crypt footer and key\n");
1366 return -1;
1367 }
1368
1369 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1370 /* If the device has no password, then just say the password is valid */
1371 rc = 0;
1372 } else {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001373 decrypt_master_key_and_upgrade(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001374 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1375 /* They match, the password is correct */
1376 rc = 0;
1377 } else {
1378 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1379 sleep(1);
1380 rc = 1;
1381 }
1382 }
1383
1384 return rc;
1385}
1386
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001387/* Initialize a crypt_mnt_ftr structure. The keysize is
1388 * defaulted to 16 bytes, and the filesystem size to 0.
1389 * Presumably, at a minimum, the caller will update the
1390 * filesystem size and crypto_type_name after calling this function.
1391 */
1392static void cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
1393{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001394 off64_t off;
1395
1396 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001397 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001398 ftr->major_version = CURRENT_MAJOR_VERSION;
1399 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001400 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001401 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001402
Kenny Rootc4c70f12013-06-14 12:11:38 -07001403 ftr->kdf_type = KDF_SCRYPT;
1404 get_device_scrypt_params(ftr);
1405
Ken Sumrall160b4d62013-04-22 12:15:39 -07001406 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1407 if (get_crypt_ftr_info(NULL, &off) == 0) {
1408 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1409 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1410 ftr->persist_data_size;
1411 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001412}
1413
Ken Sumrall29d8da82011-05-18 17:20:07 -07001414static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001415{
1416 char cmdline[256];
1417 int rc = -1;
1418
Ken Sumrall29d8da82011-05-18 17:20:07 -07001419 if (type == EXT4_FS) {
1420 snprintf(cmdline, sizeof(cmdline), "/system/bin/make_ext4fs -a /data -l %lld %s",
1421 size * 512, crypto_blkdev);
1422 SLOGI("Making empty filesystem with command %s\n", cmdline);
1423 } else if (type== FAT_FS) {
1424 snprintf(cmdline, sizeof(cmdline), "/system/bin/newfs_msdos -F 32 -O android -c 8 -s %lld %s",
1425 size, crypto_blkdev);
1426 SLOGI("Making empty filesystem with command %s\n", cmdline);
1427 } else {
1428 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1429 return -1;
1430 }
1431
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001432 if (system(cmdline)) {
1433 SLOGE("Error creating empty filesystem on %s\n", crypto_blkdev);
1434 } else {
1435 SLOGD("Successfully created empty filesystem on %s\n", crypto_blkdev);
1436 rc = 0;
1437 }
1438
1439 return rc;
1440}
1441
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001442#define CRYPT_INPLACE_BUFSIZE 4096
1443#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / 512)
Ken Sumrall29d8da82011-05-18 17:20:07 -07001444static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev, off64_t size,
1445 off64_t *size_already_done, off64_t tot_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001446{
1447 int realfd, cryptofd;
1448 char *buf[CRYPT_INPLACE_BUFSIZE];
1449 int rc = -1;
1450 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001451 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001452 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001453
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001454 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
1455 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
1456 return -1;
1457 }
1458
1459 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
1460 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1461 close(realfd);
1462 return -1;
1463 }
1464
1465 /* This is pretty much a simple loop of reading 4K, and writing 4K.
1466 * The size passed in is the number of 512 byte sectors in the filesystem.
1467 * So compute the number of whole 4K blocks we should read/write,
1468 * and the remainder.
1469 */
1470 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
1471 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001472 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
1473 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001474
1475 SLOGE("Encrypting filesystem in place...");
1476
Ken Sumrall29d8da82011-05-18 17:20:07 -07001477 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001478 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001479 /* process the majority of the filesystem in blocks */
1480 for (i=0; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001481 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001482 if (new_pct > cur_pct) {
1483 char buf[8];
1484
1485 cur_pct = new_pct;
1486 snprintf(buf, sizeof(buf), "%lld", cur_pct);
1487 property_set("vold.encrypt_progress", buf);
1488 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001489 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1490 SLOGE("Error reading real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1491 goto errout;
1492 }
1493 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1494 SLOGE("Error writing crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1495 goto errout;
1496 }
1497 }
1498
1499 /* Do any remaining sectors */
1500 for (i=0; i<remainder; i++) {
1501 if (unix_read(realfd, buf, 512) <= 0) {
1502 SLOGE("Error reading rival sectors from real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1503 goto errout;
1504 }
1505 if (unix_write(cryptofd, buf, 512) <= 0) {
1506 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1507 goto errout;
1508 }
1509 }
1510
Ken Sumrall29d8da82011-05-18 17:20:07 -07001511 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001512 rc = 0;
1513
1514errout:
1515 close(realfd);
1516 close(cryptofd);
1517
1518 return rc;
1519}
1520
1521#define CRYPTO_ENABLE_WIPE 1
1522#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001523
1524#define FRAMEWORK_BOOT_WAIT 60
1525
Ken Sumrall29d8da82011-05-18 17:20:07 -07001526static inline int should_encrypt(struct volume_info *volume)
1527{
1528 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
1529 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
1530}
1531
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001532int cryptfs_enable(char *howarg, char *passwd)
1533{
1534 int how = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001535 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN], sd_crypto_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07001536 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001537 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07001538 int rc=-1, fd, i, ret;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001539 struct crypt_mnt_ftr crypt_ftr, sd_crypt_ftr;;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001540 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001541 char tmpfs_options[PROPERTY_VALUE_MAX];
1542 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001543 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07001544 char key_loc[PROPERTY_VALUE_MAX];
1545 char fuse_sdcard[PROPERTY_VALUE_MAX];
1546 char *sd_mnt_point;
1547 char sd_blk_dev[256] = { 0 };
1548 int num_vols;
1549 struct volume_info *vol_list = 0;
1550 off64_t cur_encryption_done=0, tot_encryption_size=0;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001551
1552 property_get("ro.crypto.state", encrypted_state, "");
1553 if (strcmp(encrypted_state, "unencrypted")) {
1554 SLOGE("Device is already running encrypted, aborting");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001555 goto error_unencrypted;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001556 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001557
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001558 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001559
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001560 if (!strcmp(howarg, "wipe")) {
1561 how = CRYPTO_ENABLE_WIPE;
1562 } else if (! strcmp(howarg, "inplace")) {
1563 how = CRYPTO_ENABLE_INPLACE;
1564 } else {
1565 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08001566 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001567 }
1568
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001569 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001570
Ken Sumrall3ed82362011-01-28 23:31:16 -08001571 /* Get the size of the real block device */
1572 fd = open(real_blkdev, O_RDONLY);
1573 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
1574 SLOGE("Cannot get size of block device %s\n", real_blkdev);
1575 goto error_unencrypted;
1576 }
1577 close(fd);
1578
1579 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001580 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001581 unsigned int fs_size_sec, max_fs_size_sec;
1582
1583 fs_size_sec = get_fs_size(real_blkdev);
1584 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1585
1586 if (fs_size_sec > max_fs_size_sec) {
1587 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
1588 goto error_unencrypted;
1589 }
1590 }
1591
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001592 /* Get a wakelock as this may take a while, and we don't want the
1593 * device to sleep on us. We'll grab a partial wakelock, and if the UI
1594 * wants to keep the screen on, it can grab a full wakelock.
1595 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001596 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001597 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
1598
Jeff Sharkey7382f812012-08-23 14:08:59 -07001599 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07001600 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07001601 if (!sd_mnt_point) {
1602 sd_mnt_point = getenv("EXTERNAL_STORAGE");
1603 }
1604 if (!sd_mnt_point) {
1605 sd_mnt_point = "/mnt/sdcard";
1606 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07001607
1608 num_vols=vold_getNumDirectVolumes();
1609 vol_list = malloc(sizeof(struct volume_info) * num_vols);
1610 vold_getDirectVolumeList(vol_list);
1611
1612 for (i=0; i<num_vols; i++) {
1613 if (should_encrypt(&vol_list[i])) {
1614 fd = open(vol_list[i].blk_dev, O_RDONLY);
1615 if ( (vol_list[i].size = get_blkdev_size(fd)) == 0) {
1616 SLOGE("Cannot get size of block device %s\n", vol_list[i].blk_dev);
1617 goto error_unencrypted;
1618 }
1619 close(fd);
1620
Ken Sumrall3b170052011-07-11 15:38:57 -07001621 ret=vold_disableVol(vol_list[i].label);
Ken Sumrall319b1042011-06-14 14:01:55 -07001622 if ((ret < 0) && (ret != UNMOUNT_NOT_MOUNTED_ERR)) {
1623 /* -2 is returned when the device exists but is not currently mounted.
1624 * ignore the error and continue. */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001625 SLOGE("Failed to unmount volume %s\n", vol_list[i].label);
1626 goto error_unencrypted;
1627 }
1628 }
1629 }
1630
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001631 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001632 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001633 */
1634 property_set("vold.decrypt", "trigger_shutdown_framework");
1635 SLOGD("Just asked init to shut down class main\n");
1636
Ken Sumrall425524d2012-06-14 20:55:28 -07001637 if (vold_unmountAllAsecs()) {
1638 /* Just report the error. If any are left mounted,
1639 * umounting /data below will fail and handle the error.
1640 */
1641 SLOGE("Error unmounting internal asecs");
1642 }
1643
Ken Sumrall29d8da82011-05-18 17:20:07 -07001644 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
1645 if (!strcmp(fuse_sdcard, "true")) {
1646 /* This is a device using the fuse layer to emulate the sdcard semantics
1647 * on top of the userdata partition. vold does not manage it, it is managed
1648 * by the sdcard service. The sdcard service was killed by the property trigger
1649 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
1650 * unlike the case for vold managed devices above.
1651 */
1652 if (wait_and_unmount(sd_mnt_point)) {
1653 goto error_shutting_down;
1654 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001655 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001656
1657 /* Now unmount the /data partition. */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001658 if (wait_and_unmount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001659 goto error_shutting_down;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001660 }
1661
1662 /* Do extra work for a better UX when doing the long inplace encryption */
1663 if (how == CRYPTO_ENABLE_INPLACE) {
1664 /* Now that /data is unmounted, we need to mount a tmpfs
1665 * /data, set a property saying we're doing inplace encryption,
1666 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001667 */
Ken Sumralle5032c42012-04-01 23:58:44 -07001668 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001669 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001670 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001671 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08001672 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001673
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001674 /* restart the framework. */
1675 /* Create necessary paths on /data */
1676 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001677 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001678 }
1679
Ken Sumrall92736ef2012-10-17 20:57:14 -07001680 /* Ugh, shutting down the framework is not synchronous, so until it
1681 * can be fixed, this horrible hack will wait a moment for it all to
1682 * shut down before proceeding. Without it, some devices cannot
1683 * restart the graphics services.
1684 */
1685 sleep(2);
1686
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001687 /* startup service classes main and late_start */
1688 property_set("vold.decrypt", "trigger_restart_min_framework");
1689 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001690
Ken Sumrall7df84122011-01-18 14:04:08 -08001691 /* OK, the framework is restarted and will soon be showing a
1692 * progress bar. Time to setup an encrypted mapping, and
1693 * either write a new filesystem, or encrypt in place updating
1694 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001695 */
1696 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001697
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001698 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001699 /* Initialize a crypt_mnt_ftr for the partition */
1700 cryptfs_init_crypt_mnt_ftr(&crypt_ftr);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001701
Ken Sumrall29d8da82011-05-18 17:20:07 -07001702 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
1703 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1704 } else {
1705 crypt_ftr.fs_size = nr_sec;
1706 }
Ken Sumralld33d4172011-02-01 00:49:13 -08001707 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001708 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
1709
1710 /* Make an encrypted master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001711 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001712 SLOGE("Cannot create encrypted master key\n");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001713 goto error_unencrypted;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001714 }
1715
1716 /* Write the key to the end of the partition */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001717 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001718
Ken Sumrall160b4d62013-04-22 12:15:39 -07001719 /* If any persistent data has been remembered, save it.
1720 * If none, create a valid empty table and save that.
1721 */
1722 if (!persist_data) {
1723 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
1724 if (pdata) {
1725 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
1726 persist_data = pdata;
1727 }
1728 }
1729 if (persist_data) {
1730 save_persistent_data();
1731 }
1732
Kenny Rootc4c70f12013-06-14 12:11:38 -07001733 decrypt_master_key_and_upgrade(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001734 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
1735 "userdata");
1736
Ken Sumrall128626f2011-06-28 18:45:14 -07001737 /* The size of the userdata partition, and add in the vold volumes below */
1738 tot_encryption_size = crypt_ftr.fs_size;
1739
Ken Sumrall29d8da82011-05-18 17:20:07 -07001740 /* setup crypto mapping for all encryptable volumes handled by vold */
1741 for (i=0; i<num_vols; i++) {
1742 if (should_encrypt(&vol_list[i])) {
1743 vol_list[i].crypt_ftr = crypt_ftr; /* gotta love struct assign */
1744 vol_list[i].crypt_ftr.fs_size = vol_list[i].size;
1745 create_crypto_blk_dev(&vol_list[i].crypt_ftr, decrypted_master_key,
1746 vol_list[i].blk_dev, vol_list[i].crypto_blkdev,
1747 vol_list[i].label);
Ken Sumrall128626f2011-06-28 18:45:14 -07001748 tot_encryption_size += vol_list[i].size;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001749 }
1750 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001751
1752 if (how == CRYPTO_ENABLE_WIPE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001753 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr.fs_size, EXT4_FS);
1754 /* Encrypt all encryptable volumes handled by vold */
1755 if (!rc) {
1756 for (i=0; i<num_vols; i++) {
1757 if (should_encrypt(&vol_list[i])) {
1758 rc = cryptfs_enable_wipe(vol_list[i].crypto_blkdev,
1759 vol_list[i].crypt_ftr.fs_size, FAT_FS);
1760 }
1761 }
1762 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001763 } else if (how == CRYPTO_ENABLE_INPLACE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001764 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr.fs_size,
1765 &cur_encryption_done, tot_encryption_size);
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_inplace(vol_list[i].crypto_blkdev,
1771 vol_list[i].blk_dev,
1772 vol_list[i].crypt_ftr.fs_size,
1773 &cur_encryption_done, tot_encryption_size);
1774 }
1775 }
1776 }
1777 if (!rc) {
1778 /* The inplace routine never actually sets the progress to 100%
1779 * due to the round down nature of integer division, so set it here */
1780 property_set("vold.encrypt_progress", "100");
1781 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001782 } else {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001783 /* Shouldn't happen */
1784 SLOGE("cryptfs_enable: internal error, unknown option\n");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001785 goto error_unencrypted;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001786 }
1787
1788 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001789 delete_crypto_blk_dev("userdata");
1790 for (i=0; i<num_vols; i++) {
1791 if (should_encrypt(&vol_list[i])) {
1792 delete_crypto_blk_dev(vol_list[i].label);
1793 }
1794 }
1795
1796 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001797
1798 if (! rc) {
1799 /* Success */
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001800
Ken Sumralld33d4172011-02-01 00:49:13 -08001801 /* Clear the encryption in progres flag in the footer */
1802 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001803 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08001804
Ken Sumrall29d8da82011-05-18 17:20:07 -07001805 sleep(2); /* Give the UI a chance to show 100% progress */
Ken Sumrallc290eaf2011-03-07 23:40:35 -08001806 android_reboot(ANDROID_RB_RESTART, 0, 0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001807 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001808 char value[PROPERTY_VALUE_MAX];
1809
Ken Sumrall319369a2012-06-27 16:30:18 -07001810 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001811 if (!strcmp(value, "1")) {
1812 /* wipe data if encryption failed */
1813 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
1814 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07001815 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001816 if (fd >= 0) {
1817 write(fd, "--wipe_data", strlen("--wipe_data") + 1);
1818 close(fd);
1819 } else {
1820 SLOGE("could not open /cache/recovery/command\n");
1821 }
1822 android_reboot(ANDROID_RB_RESTART2, 0, "recovery");
1823 } else {
1824 /* set property to trigger dialog */
1825 property_set("vold.encrypt_progress", "error_partially_encrypted");
1826 release_wake_lock(lockid);
1827 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001828 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001829 }
1830
Ken Sumrall3ed82362011-01-28 23:31:16 -08001831 /* hrm, the encrypt step claims success, but the reboot failed.
1832 * This should not happen.
1833 * Set the property and return. Hope the framework can deal with it.
1834 */
1835 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001836 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001837 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08001838
1839error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07001840 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001841 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001842 if (lockid[0]) {
1843 release_wake_lock(lockid);
1844 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001845 return -1;
1846
1847error_shutting_down:
1848 /* we failed, and have not encrypted anthing, so the users's data is still intact,
1849 * but the framework is stopped and not restarted to show the error, so it's up to
1850 * vold to restart the system.
1851 */
1852 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Ken Sumrallc290eaf2011-03-07 23:40:35 -08001853 android_reboot(ANDROID_RB_RESTART, 0, 0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001854
1855 /* shouldn't get here */
1856 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001857 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001858 if (lockid[0]) {
1859 release_wake_lock(lockid);
1860 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001861 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001862}
1863
Jason parks70a4b3f2011-01-28 10:10:47 -06001864int cryptfs_changepw(char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001865{
1866 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001867 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001868
1869 /* This is only allowed after we've successfully decrypted the master key */
Jason parks70a4b3f2011-01-28 10:10:47 -06001870 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001871 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001872 return -1;
1873 }
1874
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001875 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001876 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall57b63e62011-01-17 18:29:19 -08001877 SLOGE("Error getting crypt footer and key");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001878 return -1;
1879 }
1880
Kenny Rootc4c70f12013-06-14 12:11:38 -07001881 encrypt_master_key(newpw, crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001882
Jason parks70a4b3f2011-01-28 10:10:47 -06001883 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001884 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001885
1886 return 0;
1887}
Ken Sumrall160b4d62013-04-22 12:15:39 -07001888
1889static int persist_get_key(char *fieldname, char *value)
1890{
1891 unsigned int i;
1892
1893 if (persist_data == NULL) {
1894 return -1;
1895 }
1896 for (i = 0; i < persist_data->persist_valid_entries; i++) {
1897 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
1898 /* We found it! */
1899 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
1900 return 0;
1901 }
1902 }
1903
1904 return -1;
1905}
1906
1907static int persist_set_key(char *fieldname, char *value, int encrypted)
1908{
1909 unsigned int i;
1910 unsigned int num;
1911 struct crypt_mnt_ftr crypt_ftr;
1912 unsigned int max_persistent_entries;
1913 unsigned int dsize;
1914
1915 if (persist_data == NULL) {
1916 return -1;
1917 }
1918
1919 /* If encrypted, use the values from the crypt_ftr, otherwise
1920 * use the values for the current spec.
1921 */
1922 if (encrypted) {
1923 if(get_crypt_ftr_and_key(&crypt_ftr)) {
1924 return -1;
1925 }
1926 dsize = crypt_ftr.persist_data_size;
1927 } else {
1928 dsize = CRYPT_PERSIST_DATA_SIZE;
1929 }
1930 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
1931 sizeof(struct crypt_persist_entry);
1932
1933 num = persist_data->persist_valid_entries;
1934
1935 for (i = 0; i < num; i++) {
1936 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
1937 /* We found an existing entry, update it! */
1938 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
1939 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
1940 return 0;
1941 }
1942 }
1943
1944 /* We didn't find it, add it to the end, if there is room */
1945 if (persist_data->persist_valid_entries < max_persistent_entries) {
1946 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
1947 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
1948 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
1949 persist_data->persist_valid_entries++;
1950 return 0;
1951 }
1952
1953 return -1;
1954}
1955
1956/* Return the value of the specified field. */
1957int cryptfs_getfield(char *fieldname, char *value, int len)
1958{
1959 char temp_value[PROPERTY_VALUE_MAX];
1960 char real_blkdev[MAXPATHLEN];
1961 /* 0 is success, 1 is not encrypted,
1962 * -1 is value not set, -2 is any other error
1963 */
1964 int rc = -2;
1965
1966 if (persist_data == NULL) {
1967 load_persistent_data();
1968 if (persist_data == NULL) {
1969 SLOGE("Getfield error, cannot load persistent data");
1970 goto out;
1971 }
1972 }
1973
1974 if (!persist_get_key(fieldname, temp_value)) {
1975 /* We found it, copy it to the caller's buffer and return */
1976 strlcpy(value, temp_value, len);
1977 rc = 0;
1978 } else {
1979 /* Sadness, it's not there. Return the error */
1980 rc = -1;
1981 }
1982
1983out:
1984 return rc;
1985}
1986
1987/* Set the value of the specified field. */
1988int cryptfs_setfield(char *fieldname, char *value)
1989{
1990 struct crypt_persist_data stored_pdata;
1991 struct crypt_persist_data *pdata_p;
1992 struct crypt_mnt_ftr crypt_ftr;
1993 char encrypted_state[PROPERTY_VALUE_MAX];
1994 /* 0 is success, -1 is an error */
1995 int rc = -1;
1996 int encrypted = 0;
1997
1998 if (persist_data == NULL) {
1999 load_persistent_data();
2000 if (persist_data == NULL) {
2001 SLOGE("Setfield error, cannot load persistent data");
2002 goto out;
2003 }
2004 }
2005
2006 property_get("ro.crypto.state", encrypted_state, "");
2007 if (!strcmp(encrypted_state, "encrypted") ) {
2008 encrypted = 1;
2009 }
2010
2011 if (persist_set_key(fieldname, value, encrypted)) {
2012 goto out;
2013 }
2014
2015 /* If we are running encrypted, save the persistent data now */
2016 if (encrypted) {
2017 if (save_persistent_data()) {
2018 SLOGE("Setfield error, cannot save persistent data");
2019 goto out;
2020 }
2021 }
2022
2023 rc = 0;
2024
2025out:
2026 return rc;
2027}