blob: 1e51fd54af8701b2cd914a048c13af5f98ea688d [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 */
Kenny Root2947e342013-08-14 15:54:49 -0700120 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
121 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700122 i++, token = strtok_r(NULL, ":", &saveptr)) {
123 char *endptr;
124 params[i] = strtol(token, &endptr, 10);
125
126 /*
127 * Check that there was a valid number and it's 8-bit. If not,
128 * break out and the end check will take the default values.
129 */
130 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
131 break;
132 }
133 }
134
135 /*
136 * If there were not enough tokens or a token was malformed (not an
137 * integer), it will end up here and the default parameters can be
138 * taken.
139 */
140 if ((i != 3) || (token != NULL)) {
141 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
142 memcpy(params, default_params, sizeof(params));
143 }
144 }
145
146 ftr->N_factor = params[0];
147 ftr->r_factor = params[1];
148 ftr->p_factor = params[2];
149}
150
Ken Sumrall3ed82362011-01-28 23:31:16 -0800151static unsigned int get_fs_size(char *dev)
152{
153 int fd, block_size;
154 struct ext4_super_block sb;
155 off64_t len;
156
157 if ((fd = open(dev, O_RDONLY)) < 0) {
158 SLOGE("Cannot open device to get filesystem size ");
159 return 0;
160 }
161
162 if (lseek64(fd, 1024, SEEK_SET) < 0) {
163 SLOGE("Cannot seek to superblock");
164 return 0;
165 }
166
167 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
168 SLOGE("Cannot read superblock");
169 return 0;
170 }
171
172 close(fd);
173
174 block_size = 1024 << sb.s_log_block_size;
175 /* compute length in bytes */
176 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
177
178 /* return length in sectors */
179 return (unsigned int) (len / 512);
180}
181
Ken Sumrall160b4d62013-04-22 12:15:39 -0700182static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
183{
184 static int cached_data = 0;
185 static off64_t cached_off = 0;
186 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
187 int fd;
188 char key_loc[PROPERTY_VALUE_MAX];
189 char real_blkdev[PROPERTY_VALUE_MAX];
190 unsigned int nr_sec;
191 int rc = -1;
192
193 if (!cached_data) {
194 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
195
196 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
197 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
198 SLOGE("Cannot open real block device %s\n", real_blkdev);
199 return -1;
200 }
201
202 if ((nr_sec = get_blkdev_size(fd))) {
203 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
204 * encryption info footer and key, and plenty of bytes to spare for future
205 * growth.
206 */
207 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
208 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
209 cached_data = 1;
210 } else {
211 SLOGE("Cannot get size of block device %s\n", real_blkdev);
212 }
213 close(fd);
214 } else {
215 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
216 cached_off = 0;
217 cached_data = 1;
218 }
219 }
220
221 if (cached_data) {
222 if (metadata_fname) {
223 *metadata_fname = cached_metadata_fname;
224 }
225 if (off) {
226 *off = cached_off;
227 }
228 rc = 0;
229 }
230
231 return rc;
232}
233
Ken Sumralle8744072011-01-18 22:01:55 -0800234/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800235 * update the failed mount count but not change the key.
236 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700237static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800238{
239 int fd;
240 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700241 /* starting_off is set to the SEEK_SET offset
242 * where the crypto structure starts
243 */
244 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800245 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700246 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700247 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall3be890f2011-09-14 16:53:46 -0700248 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800249
Ken Sumrall160b4d62013-04-22 12:15:39 -0700250 if (get_crypt_ftr_info(&fname, &starting_off)) {
251 SLOGE("Unable to get crypt_ftr_info\n");
252 return -1;
253 }
254 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700255 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700256 return -1;
257 }
258 if ( (fd = open(fname, O_RDWR)) < 0) {
259 SLOGE("Cannot open footer file %s\n", fname);
260 return -1;
261 }
262
263 /* Seek to the start of the crypt footer */
264 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
265 SLOGE("Cannot seek to real block device footer\n");
266 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800267 }
268
269 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
270 SLOGE("Cannot write real block device footer\n");
271 goto errout;
272 }
273
Ken Sumrall3be890f2011-09-14 16:53:46 -0700274 fstat(fd, &statbuf);
275 /* If the keys are kept on a raw block device, do not try to truncate it. */
276 if (S_ISREG(statbuf.st_mode) && (key_loc[0] == '/')) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700277 if (ftruncate(fd, 0x4000)) {
Ken Sumrall3be890f2011-09-14 16:53:46 -0700278 SLOGE("Cannot set footer file size\n", fname);
Ken Sumralle8744072011-01-18 22:01:55 -0800279 goto errout;
280 }
281 }
282
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800283 /* Success! */
284 rc = 0;
285
286errout:
287 close(fd);
288 return rc;
289
290}
291
Ken Sumrall160b4d62013-04-22 12:15:39 -0700292static inline int unix_read(int fd, void* buff, int len)
293{
294 return TEMP_FAILURE_RETRY(read(fd, buff, len));
295}
296
297static inline int unix_write(int fd, const void* buff, int len)
298{
299 return TEMP_FAILURE_RETRY(write(fd, buff, len));
300}
301
302static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
303{
304 memset(pdata, 0, len);
305 pdata->persist_magic = PERSIST_DATA_MAGIC;
306 pdata->persist_valid_entries = 0;
307}
308
309/* A routine to update the passed in crypt_ftr to the lastest version.
310 * fd is open read/write on the device that holds the crypto footer and persistent
311 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
312 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
313 */
314static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
315{
Kenny Root7434b312013-06-14 11:29:53 -0700316 int orig_major = crypt_ftr->major_version;
317 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700318
Kenny Root7434b312013-06-14 11:29:53 -0700319 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
320 struct crypt_persist_data *pdata;
321 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700322
Kenny Rootc4c70f12013-06-14 12:11:38 -0700323 SLOGW("upgrading crypto footer to 1.1");
324
Kenny Root7434b312013-06-14 11:29:53 -0700325 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
326 if (pdata == NULL) {
327 SLOGE("Cannot allocate persisent data\n");
328 return;
329 }
330 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
331
332 /* Need to initialize the persistent data area */
333 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
334 SLOGE("Cannot seek to persisent data offset\n");
335 return;
336 }
337 /* Write all zeros to the first copy, making it invalid */
338 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
339
340 /* Write a valid but empty structure to the second copy */
341 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
342 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
343
344 /* Update the footer */
345 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
346 crypt_ftr->persist_data_offset[0] = pdata_offset;
347 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
348 crypt_ftr->minor_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700349 }
350
Kenny Rootc4c70f12013-06-14 12:11:38 -0700351 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version)) {
352 SLOGW("upgrading crypto footer to 1.2");
353 crypt_ftr->kdf_type = KDF_PBKDF2;
354 get_device_scrypt_params(crypt_ftr);
355 crypt_ftr->minor_version = 2;
356 }
357
Kenny Root7434b312013-06-14 11:29:53 -0700358 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
359 if (lseek64(fd, offset, SEEK_SET) == -1) {
360 SLOGE("Cannot seek to crypt footer\n");
361 return;
362 }
363 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700364 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700365}
366
367
368static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800369{
370 int fd;
371 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700372 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800373 int rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700374 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700375 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700376 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800377
Ken Sumrall160b4d62013-04-22 12:15:39 -0700378 if (get_crypt_ftr_info(&fname, &starting_off)) {
379 SLOGE("Unable to get crypt_ftr_info\n");
380 return -1;
381 }
382 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700383 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700384 return -1;
385 }
386 if ( (fd = open(fname, O_RDWR)) < 0) {
387 SLOGE("Cannot open footer file %s\n", fname);
388 return -1;
389 }
390
391 /* Make sure it's 16 Kbytes in length */
392 fstat(fd, &statbuf);
393 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
394 SLOGE("footer file %s is not the expected size!\n", fname);
395 goto errout;
396 }
397
398 /* Seek to the start of the crypt footer */
399 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
400 SLOGE("Cannot seek to real block device footer\n");
401 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800402 }
403
404 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
405 SLOGE("Cannot read real block device footer\n");
406 goto errout;
407 }
408
409 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700410 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800411 goto errout;
412 }
413
Kenny Rootc96a5f82013-06-14 12:08:28 -0700414 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
415 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
416 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800417 goto errout;
418 }
419
Kenny Rootc96a5f82013-06-14 12:08:28 -0700420 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
421 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
422 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800423 }
424
Ken Sumrall160b4d62013-04-22 12:15:39 -0700425 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
426 * copy on disk before returning.
427 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700428 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700429 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800430 }
431
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800432 /* Success! */
433 rc = 0;
434
435errout:
436 close(fd);
437 return rc;
438}
439
Ken Sumrall160b4d62013-04-22 12:15:39 -0700440static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
441{
442 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
443 crypt_ftr->persist_data_offset[1]) {
444 SLOGE("Crypt_ftr persist data regions overlap");
445 return -1;
446 }
447
448 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
449 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
450 return -1;
451 }
452
453 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
454 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
455 CRYPT_FOOTER_OFFSET) {
456 SLOGE("Persistent data extends past crypto footer");
457 return -1;
458 }
459
460 return 0;
461}
462
463static int load_persistent_data(void)
464{
465 struct crypt_mnt_ftr crypt_ftr;
466 struct crypt_persist_data *pdata = NULL;
467 char encrypted_state[PROPERTY_VALUE_MAX];
468 char *fname;
469 int found = 0;
470 int fd;
471 int ret;
472 int i;
473
474 if (persist_data) {
475 /* Nothing to do, we've already loaded or initialized it */
476 return 0;
477 }
478
479
480 /* If not encrypted, just allocate an empty table and initialize it */
481 property_get("ro.crypto.state", encrypted_state, "");
482 if (strcmp(encrypted_state, "encrypted") ) {
483 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
484 if (pdata) {
485 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
486 persist_data = pdata;
487 return 0;
488 }
489 return -1;
490 }
491
492 if(get_crypt_ftr_and_key(&crypt_ftr)) {
493 return -1;
494 }
495
496 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
497 SLOGE("Crypt_ftr version doesn't support persistent data");
498 return -1;
499 }
500
501 if (get_crypt_ftr_info(&fname, NULL)) {
502 return -1;
503 }
504
505 ret = validate_persistent_data_storage(&crypt_ftr);
506 if (ret) {
507 return -1;
508 }
509
510 fd = open(fname, O_RDONLY);
511 if (fd < 0) {
512 SLOGE("Cannot open %s metadata file", fname);
513 return -1;
514 }
515
516 if (persist_data == NULL) {
517 pdata = malloc(crypt_ftr.persist_data_size);
518 if (pdata == NULL) {
519 SLOGE("Cannot allocate memory for persistent data");
520 goto err;
521 }
522 }
523
524 for (i = 0; i < 2; i++) {
525 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
526 SLOGE("Cannot seek to read persistent data on %s", fname);
527 goto err2;
528 }
529 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
530 SLOGE("Error reading persistent data on iteration %d", i);
531 goto err2;
532 }
533 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
534 found = 1;
535 break;
536 }
537 }
538
539 if (!found) {
540 SLOGI("Could not find valid persistent data, creating");
541 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
542 }
543
544 /* Success */
545 persist_data = pdata;
546 close(fd);
547 return 0;
548
549err2:
550 free(pdata);
551
552err:
553 close(fd);
554 return -1;
555}
556
557static int save_persistent_data(void)
558{
559 struct crypt_mnt_ftr crypt_ftr;
560 struct crypt_persist_data *pdata;
561 char *fname;
562 off64_t write_offset;
563 off64_t erase_offset;
564 int found = 0;
565 int fd;
566 int ret;
567
568 if (persist_data == NULL) {
569 SLOGE("No persistent data to save");
570 return -1;
571 }
572
573 if(get_crypt_ftr_and_key(&crypt_ftr)) {
574 return -1;
575 }
576
577 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
578 SLOGE("Crypt_ftr version doesn't support persistent data");
579 return -1;
580 }
581
582 ret = validate_persistent_data_storage(&crypt_ftr);
583 if (ret) {
584 return -1;
585 }
586
587 if (get_crypt_ftr_info(&fname, NULL)) {
588 return -1;
589 }
590
591 fd = open(fname, O_RDWR);
592 if (fd < 0) {
593 SLOGE("Cannot open %s metadata file", fname);
594 return -1;
595 }
596
597 pdata = malloc(crypt_ftr.persist_data_size);
598 if (pdata == NULL) {
599 SLOGE("Cannot allocate persistant data");
600 goto err;
601 }
602
603 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
604 SLOGE("Cannot seek to read persistent data on %s", fname);
605 goto err2;
606 }
607
608 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
609 SLOGE("Error reading persistent data before save");
610 goto err2;
611 }
612
613 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
614 /* The first copy is the curent valid copy, so write to
615 * the second copy and erase this one */
616 write_offset = crypt_ftr.persist_data_offset[1];
617 erase_offset = crypt_ftr.persist_data_offset[0];
618 } else {
619 /* The second copy must be the valid copy, so write to
620 * the first copy, and erase the second */
621 write_offset = crypt_ftr.persist_data_offset[0];
622 erase_offset = crypt_ftr.persist_data_offset[1];
623 }
624
625 /* Write the new copy first, if successful, then erase the old copy */
626 if (lseek(fd, write_offset, SEEK_SET) < 0) {
627 SLOGE("Cannot seek to write persistent data");
628 goto err2;
629 }
630 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
631 (int) crypt_ftr.persist_data_size) {
632 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
633 SLOGE("Cannot seek to erase previous persistent data");
634 goto err2;
635 }
636 fsync(fd);
637 memset(pdata, 0, crypt_ftr.persist_data_size);
638 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
639 (int) crypt_ftr.persist_data_size) {
640 SLOGE("Cannot write to erase previous persistent data");
641 goto err2;
642 }
643 fsync(fd);
644 } else {
645 SLOGE("Cannot write to save persistent data");
646 goto err2;
647 }
648
649 /* Success */
650 free(pdata);
651 close(fd);
652 return 0;
653
654err2:
655 free(pdata);
656err:
657 close(fd);
658 return -1;
659}
660
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800661/* Convert a binary key of specified length into an ascii hex string equivalent,
662 * without the leading 0x and with null termination
663 */
664void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
665 char *master_key_ascii)
666{
667 unsigned int i, a;
668 unsigned char nibble;
669
670 for (i=0, a=0; i<keysize; i++, a+=2) {
671 /* For each byte, write out two ascii hex digits */
672 nibble = (master_key[i] >> 4) & 0xf;
673 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
674
675 nibble = master_key[i] & 0xf;
676 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
677 }
678
679 /* Add the null termination */
680 master_key_ascii[a] = '\0';
681
682}
683
Ken Sumralldb5e0262013-02-05 17:39:48 -0800684static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
685 char *real_blk_name, const char *name, int fd,
686 char *extra_params)
687{
688 char buffer[DM_CRYPT_BUF_SIZE];
689 struct dm_ioctl *io;
690 struct dm_target_spec *tgt;
691 char *crypt_params;
692 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
693 int i;
694
695 io = (struct dm_ioctl *) buffer;
696
697 /* Load the mapping table for this device */
698 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
699
700 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
701 io->target_count = 1;
702 tgt->status = 0;
703 tgt->sector_start = 0;
704 tgt->length = crypt_ftr->fs_size;
705 strcpy(tgt->target_type, "crypt");
706
707 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
708 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
709 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
710 master_key_ascii, real_blk_name, extra_params);
711 crypt_params += strlen(crypt_params) + 1;
712 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
713 tgt->next = crypt_params - buffer;
714
715 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
716 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
717 break;
718 }
719 usleep(500000);
720 }
721
722 if (i == TABLE_LOAD_RETRIES) {
723 /* We failed to load the table, return an error */
724 return -1;
725 } else {
726 return i + 1;
727 }
728}
729
730
731static int get_dm_crypt_version(int fd, const char *name, int *version)
732{
733 char buffer[DM_CRYPT_BUF_SIZE];
734 struct dm_ioctl *io;
735 struct dm_target_versions *v;
736 int i;
737
738 io = (struct dm_ioctl *) buffer;
739
740 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
741
742 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
743 return -1;
744 }
745
746 /* Iterate over the returned versions, looking for name of "crypt".
747 * When found, get and return the version.
748 */
749 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
750 while (v->next) {
751 if (! strcmp(v->name, "crypt")) {
752 /* We found the crypt driver, return the version, and get out */
753 version[0] = v->version[0];
754 version[1] = v->version[1];
755 version[2] = v->version[2];
756 return 0;
757 }
758 v = (struct dm_target_versions *)(((char *)v) + v->next);
759 }
760
761 return -1;
762}
763
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800764static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -0700765 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800766{
767 char buffer[DM_CRYPT_BUF_SIZE];
768 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
769 char *crypt_params;
770 struct dm_ioctl *io;
771 struct dm_target_spec *tgt;
772 unsigned int minor;
773 int fd;
Ken Sumralle919efe2012-09-29 17:07:41 -0700774 int i;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800775 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800776 int version[3];
777 char *extra_params;
778 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800779
780 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
781 SLOGE("Cannot open device-mapper\n");
782 goto errout;
783 }
784
785 io = (struct dm_ioctl *) buffer;
786
787 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
788 if (ioctl(fd, DM_DEV_CREATE, io)) {
789 SLOGE("Cannot create dm-crypt device\n");
790 goto errout;
791 }
792
793 /* Get the device status, in particular, the name of it's device file */
794 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
795 if (ioctl(fd, DM_DEV_STATUS, io)) {
796 SLOGE("Cannot retrieve dm-crypt device status\n");
797 goto errout;
798 }
799 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
800 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
801
Ken Sumralldb5e0262013-02-05 17:39:48 -0800802 extra_params = "";
803 if (! get_dm_crypt_version(fd, name, version)) {
804 /* Support for allow_discards was added in version 1.11.0 */
805 if ((version[0] >= 2) ||
806 ((version[0] == 1) && (version[1] >= 11))) {
807 extra_params = "1 allow_discards";
808 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
809 }
Ken Sumralle919efe2012-09-29 17:07:41 -0700810 }
811
Ken Sumralldb5e0262013-02-05 17:39:48 -0800812 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
813 fd, extra_params);
814 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800815 SLOGE("Cannot load dm-crypt mapping table.\n");
816 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800817 } else if (load_count > 1) {
818 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800819 }
820
821 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -0800822 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800823
824 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
825 SLOGE("Cannot resume the dm-crypt device\n");
826 goto errout;
827 }
828
829 /* We made it here with no errors. Woot! */
830 retval = 0;
831
832errout:
833 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
834
835 return retval;
836}
837
Ken Sumrall29d8da82011-05-18 17:20:07 -0700838static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800839{
840 int fd;
841 char buffer[DM_CRYPT_BUF_SIZE];
842 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800843 int retval = -1;
844
845 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
846 SLOGE("Cannot open device-mapper\n");
847 goto errout;
848 }
849
850 io = (struct dm_ioctl *) buffer;
851
852 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
853 if (ioctl(fd, DM_DEV_REMOVE, io)) {
854 SLOGE("Cannot remove dm-crypt device\n");
855 goto errout;
856 }
857
858 /* We made it here with no errors. Woot! */
859 retval = 0;
860
861errout:
862 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
863
864 return retval;
865
866}
867
Kenny Rootc4c70f12013-06-14 12:11:38 -0700868static void pbkdf2(char *passwd, unsigned char *salt, unsigned char *ikey, void *params) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800869 /* Turn the password into a key and IV that can decrypt the master key */
Ken Sumralle8744072011-01-18 22:01:55 -0800870 PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800871 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800872}
873
Kenny Rootc4c70f12013-06-14 12:11:38 -0700874static void scrypt(char *passwd, unsigned char *salt, unsigned char *ikey, void *params) {
875 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
876
877 int N = 1 << ftr->N_factor;
878 int r = 1 << ftr->r_factor;
879 int p = 1 << ftr->p_factor;
880
881 /* Turn the password into a key and IV that can decrypt the master key */
882 crypto_scrypt((unsigned char *) passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
883 KEY_LEN_BYTES + IV_LEN_BYTES);
884}
885
Ken Sumralle8744072011-01-18 22:01:55 -0800886static int encrypt_master_key(char *passwd, unsigned char *salt,
887 unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700888 unsigned char *encrypted_master_key,
889 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800890{
891 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
892 EVP_CIPHER_CTX e_ctx;
893 int encrypted_len, final_len;
894
895 /* Turn the password into a key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700896 get_device_scrypt_params(crypt_ftr);
897 scrypt(passwd, salt, ikey, crypt_ftr);
898
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800899 /* Initialize the decryption engine */
900 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
901 SLOGE("EVP_EncryptInit failed\n");
902 return -1;
903 }
904 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800905
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800906 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800907 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
908 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800909 SLOGE("EVP_EncryptUpdate failed\n");
910 return -1;
911 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800912 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800913 SLOGE("EVP_EncryptFinal failed\n");
914 return -1;
915 }
916
917 if (encrypted_len + final_len != KEY_LEN_BYTES) {
918 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
919 return -1;
920 } else {
921 return 0;
922 }
923}
924
Ken Sumralle8744072011-01-18 22:01:55 -0800925static int decrypt_master_key(char *passwd, unsigned char *salt,
926 unsigned char *encrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700927 unsigned char *decrypted_master_key,
928 kdf_func kdf, void *kdf_params)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800929{
930 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 -0800931 EVP_CIPHER_CTX d_ctx;
932 int decrypted_len, final_len;
933
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800934 /* Turn the password into a key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700935 kdf(passwd, salt, ikey, kdf_params);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800936
937 /* Initialize the decryption engine */
938 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
939 return -1;
940 }
941 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
942 /* Decrypt the master key */
943 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
944 encrypted_master_key, KEY_LEN_BYTES)) {
945 return -1;
946 }
947 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
948 return -1;
949 }
950
951 if (decrypted_len + final_len != KEY_LEN_BYTES) {
952 return -1;
953 } else {
954 return 0;
955 }
956}
957
Kenny Rootc4c70f12013-06-14 12:11:38 -0700958static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800959{
Kenny Rootc4c70f12013-06-14 12:11:38 -0700960 if (ftr->kdf_type == KDF_SCRYPT) {
961 *kdf = scrypt;
962 *kdf_params = ftr;
963 } else {
964 *kdf = pbkdf2;
965 *kdf_params = NULL;
966 }
967}
968
969static int decrypt_master_key_and_upgrade(char *passwd, unsigned char *decrypted_master_key,
970 struct crypt_mnt_ftr *crypt_ftr)
971{
972 kdf_func kdf;
973 void *kdf_params;
974 int ret;
975
976 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
977 ret = decrypt_master_key(passwd, crypt_ftr->salt, crypt_ftr->master_key, decrypted_master_key, kdf,
978 kdf_params);
979 if (ret != 0) {
980 SLOGW("failure decrypting master key");
981 return ret;
982 }
983
984 /*
985 * Upgrade if we're not using the latest KDF.
986 */
987 if (crypt_ftr->kdf_type != KDF_SCRYPT) {
988 crypt_ftr->kdf_type = KDF_SCRYPT;
989 encrypt_master_key(passwd, crypt_ftr->salt, decrypted_master_key, crypt_ftr->master_key,
990 crypt_ftr);
991 put_crypt_ftr_and_key(crypt_ftr);
992 }
993
994 return ret;
995}
996
997static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
998 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800999 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001000 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001001 EVP_CIPHER_CTX e_ctx;
1002 int encrypted_len, final_len;
1003
1004 /* Get some random bits for a key */
1005 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001006 read(fd, key_buf, sizeof(key_buf));
1007 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001008 close(fd);
1009
1010 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001011 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001012}
1013
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001014static int wait_and_unmount(char *mountpoint)
1015{
1016 int i, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001017#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001018
1019 /* Now umount the tmpfs filesystem */
1020 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
1021 if (umount(mountpoint)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001022 if (errno == EINVAL) {
1023 /* EINVAL is returned if the directory is not a mountpoint,
1024 * i.e. there is no filesystem mounted there. So just get out.
1025 */
1026 break;
1027 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001028 sleep(1);
1029 i++;
1030 } else {
1031 break;
1032 }
1033 }
1034
1035 if (i < WAIT_UNMOUNT_COUNT) {
1036 SLOGD("unmounting %s succeeded\n", mountpoint);
1037 rc = 0;
1038 } else {
1039 SLOGE("unmounting %s failed\n", mountpoint);
1040 rc = -1;
1041 }
1042
1043 return rc;
1044}
1045
Ken Sumrallc5872692013-05-14 15:26:31 -07001046#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001047static int prep_data_fs(void)
1048{
1049 int i;
1050
1051 /* Do the prep of the /data filesystem */
1052 property_set("vold.post_fs_data_done", "0");
1053 property_set("vold.decrypt", "trigger_post_fs_data");
1054 SLOGD("Just triggered post_fs_data\n");
1055
Ken Sumrallc5872692013-05-14 15:26:31 -07001056 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001057 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001058 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001059
1060 property_get("vold.post_fs_data_done", p, "0");
1061 if (*p == '1') {
1062 break;
1063 } else {
1064 usleep(250000);
1065 }
1066 }
1067 if (i == DATA_PREP_TIMEOUT) {
1068 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001069 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001070 return -1;
1071 } else {
1072 SLOGD("post_fs_data done\n");
1073 return 0;
1074 }
1075}
1076
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001077int cryptfs_restart(void)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001078{
1079 char fs_type[32];
1080 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001081 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001082 char fs_options[256];
1083 unsigned long mnt_flags;
1084 struct stat statbuf;
1085 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001086 static int restart_successful = 0;
1087
1088 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001089 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001090 SLOGE("Encrypted filesystem not validated, aborting");
1091 return -1;
1092 }
1093
1094 if (restart_successful) {
1095 SLOGE("System already restarted with encrypted disk, aborting");
1096 return -1;
1097 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001098
1099 /* Here is where we shut down the framework. The init scripts
1100 * start all services in one of three classes: core, main or late_start.
1101 * On boot, we start core and main. Now, we stop main, but not core,
1102 * as core includes vold and a few other really important things that
1103 * we need to keep running. Once main has stopped, we should be able
1104 * to umount the tmpfs /data, then mount the encrypted /data.
1105 * We then restart the class main, and also the class late_start.
1106 * At the moment, I've only put a few things in late_start that I know
1107 * are not needed to bring up the framework, and that also cause problems
1108 * with unmounting the tmpfs /data, but I hope to add add more services
1109 * to the late_start class as we optimize this to decrease the delay
1110 * till the user is asked for the password to the filesystem.
1111 */
1112
1113 /* The init files are setup to stop the class main when vold.decrypt is
1114 * set to trigger_reset_main.
1115 */
1116 property_set("vold.decrypt", "trigger_reset_main");
1117 SLOGD("Just asked init to shut down class main\n");
1118
Ken Sumrall92736ef2012-10-17 20:57:14 -07001119 /* Ugh, shutting down the framework is not synchronous, so until it
1120 * can be fixed, this horrible hack will wait a moment for it all to
1121 * shut down before proceeding. Without it, some devices cannot
1122 * restart the graphics services.
1123 */
1124 sleep(2);
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001125
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001126 /* Now that the framework is shutdown, we should be able to umount()
1127 * the tmpfs filesystem, and mount the real one.
1128 */
1129
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001130 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1131 if (strlen(crypto_blkdev) == 0) {
1132 SLOGE("fs_crypto_blkdev not set\n");
1133 return -1;
1134 }
1135
Ken Sumralle5032c42012-04-01 23:58:44 -07001136 if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
1137 /* If that succeeded, then mount the decrypted filesystem */
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001138 fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001139
Ken Sumralle5032c42012-04-01 23:58:44 -07001140 property_set("vold.decrypt", "trigger_load_persist_props");
1141 /* Create necessary paths on /data */
1142 if (prep_data_fs()) {
1143 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001144 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001145
1146 /* startup service classes main and late_start */
1147 property_set("vold.decrypt", "trigger_restart_framework");
1148 SLOGD("Just triggered restart_framework\n");
1149
1150 /* Give it a few moments to get started */
1151 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001152 }
1153
Ken Sumrall0cc16632011-01-18 20:32:26 -08001154 if (rc == 0) {
1155 restart_successful = 1;
1156 }
1157
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001158 return rc;
1159}
1160
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001161static int do_crypto_complete(char *mount_point)
1162{
1163 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001164 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001165 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001166
1167 property_get("ro.crypto.state", encrypted_state, "");
1168 if (strcmp(encrypted_state, "encrypted") ) {
1169 SLOGE("not running with encryption, aborting");
1170 return 1;
1171 }
1172
Ken Sumrall160b4d62013-04-22 12:15:39 -07001173 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001174 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001175
Ken Sumralle1a45852011-12-14 21:24:27 -08001176 /*
1177 * Only report this error if key_loc is a file and it exists.
1178 * If the device was never encrypted, and /data is not mountable for
1179 * some reason, returning 1 should prevent the UI from presenting the
1180 * a "enter password" screen, or worse, a "press button to wipe the
1181 * device" screen.
1182 */
1183 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1184 SLOGE("master key file does not exist, aborting");
1185 return 1;
1186 } else {
1187 SLOGE("Error getting crypt footer and key\n");
1188 return -1;
1189 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001190 }
1191
1192 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1193 SLOGE("Encryption process didn't finish successfully\n");
1194 return -2; /* -2 is the clue to the UI that there is no usable data on the disk,
1195 * and give the user an option to wipe the disk */
1196 }
1197
1198 /* We passed the test! We shall diminish, and return to the west */
1199 return 0;
1200}
1201
Ken Sumrall29d8da82011-05-18 17:20:07 -07001202static int test_mount_encrypted_fs(char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001203{
1204 struct crypt_mnt_ftr crypt_ftr;
1205 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001206 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001207 char crypto_blkdev[MAXPATHLEN];
1208 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001209 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001210 unsigned int orig_failed_decrypt_count;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001211 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001212 int rc;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001213 kdf_func kdf;
1214 void *kdf_params;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001215
Ken Sumrall0cc16632011-01-18 20:32:26 -08001216 property_get("ro.crypto.state", encrypted_state, "");
Jason parks70a4b3f2011-01-28 10:10:47 -06001217 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001218 SLOGE("encrypted fs already validated or not running with encryption, aborting");
1219 return -1;
1220 }
1221
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001222 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001223
Ken Sumrall160b4d62013-04-22 12:15:39 -07001224 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001225 SLOGE("Error getting crypt footer and key\n");
1226 return -1;
1227 }
Ken Sumralld33d4172011-02-01 00:49:13 -08001228
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001229 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr.fs_size);
1230 orig_failed_decrypt_count = crypt_ftr.failed_decrypt_count;
1231
1232 if (! (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001233 decrypt_master_key_and_upgrade(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001234 }
1235
1236 if (create_crypto_blk_dev(&crypt_ftr, decrypted_master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -07001237 real_blkdev, crypto_blkdev, label)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001238 SLOGE("Error creating decrypted block device\n");
1239 return -1;
1240 }
1241
Alex Klyubin707795a2013-05-10 15:17:07 -07001242 /* If init detects an encrypted filesystem, it writes a file for each such
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001243 * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
1244 * files and passes that data to me */
1245 /* Create a tmp mount point to try mounting the decryptd fs
1246 * Since we're here, the mount_point should be a tmpfs filesystem, so make
1247 * a directory in it to test mount the decrypted filesystem.
1248 */
1249 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1250 mkdir(tmp_mount_point, 0755);
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001251 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001252 SLOGE("Error temp mounting decrypted block device\n");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001253 delete_crypto_blk_dev(label);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001254 crypt_ftr.failed_decrypt_count++;
1255 } else {
1256 /* Success, so just umount and we'll mount it properly when we restart
1257 * the framework.
1258 */
1259 umount(tmp_mount_point);
1260 crypt_ftr.failed_decrypt_count = 0;
1261 }
1262
1263 if (orig_failed_decrypt_count != crypt_ftr.failed_decrypt_count) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001264 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001265 }
1266
1267 if (crypt_ftr.failed_decrypt_count) {
1268 /* We failed to mount the device, so return an error */
1269 rc = crypt_ftr.failed_decrypt_count;
1270
1271 } else {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001272 /* Woot! Success! Save the name of the crypto block device
1273 * so we can mount it when restarting the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001274 */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001275 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001276
1277 /* Also save a the master key so we can reencrypted the key
1278 * the key when we want to change the password on it.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001279 */
Jason parks70a4b3f2011-01-28 10:10:47 -06001280 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001281 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001282 master_key_saved = 1;
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001283 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001284 }
1285
1286 return rc;
1287}
1288
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001289/* Called by vold when it wants to undo the crypto mapping of a volume it
1290 * manages. This is usually in response to a factory reset, when we want
1291 * to undo the crypto mapping so the volume is formatted in the clear.
1292 */
1293int cryptfs_revert_volume(const char *label)
1294{
1295 return delete_crypto_blk_dev((char *)label);
1296}
1297
Ken Sumrall29d8da82011-05-18 17:20:07 -07001298/*
1299 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1300 * Setup a dm-crypt mapping, use the saved master key from
1301 * setting up the /data mapping, and return the new device path.
1302 */
1303int cryptfs_setup_volume(const char *label, int major, int minor,
1304 char *crypto_sys_path, unsigned int max_path,
1305 int *new_major, int *new_minor)
1306{
1307 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1308 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001309 struct stat statbuf;
1310 int nr_sec, fd;
1311
1312 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1313
Ken Sumrall160b4d62013-04-22 12:15:39 -07001314 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001315
1316 /* Update the fs_size field to be the size of the volume */
1317 fd = open(real_blkdev, O_RDONLY);
1318 nr_sec = get_blkdev_size(fd);
1319 close(fd);
1320 if (nr_sec == 0) {
1321 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1322 return -1;
1323 }
1324
1325 sd_crypt_ftr.fs_size = nr_sec;
1326 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1327 crypto_blkdev, label);
1328
1329 stat(crypto_blkdev, &statbuf);
1330 *new_major = MAJOR(statbuf.st_rdev);
1331 *new_minor = MINOR(statbuf.st_rdev);
1332
1333 /* Create path to sys entry for this block device */
1334 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1335
1336 return 0;
1337}
1338
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001339int cryptfs_crypto_complete(void)
1340{
1341 return do_crypto_complete("/data");
1342}
1343
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001344int cryptfs_check_passwd(char *passwd)
1345{
1346 int rc = -1;
1347
Ken Sumrall29d8da82011-05-18 17:20:07 -07001348 rc = test_mount_encrypted_fs(passwd, DATA_MNT_POINT, "userdata");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001349
1350 return rc;
1351}
1352
Ken Sumrall3ad90722011-10-04 20:38:29 -07001353int cryptfs_verify_passwd(char *passwd)
1354{
1355 struct crypt_mnt_ftr crypt_ftr;
1356 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001357 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001358 char encrypted_state[PROPERTY_VALUE_MAX];
1359 int rc;
1360
1361 property_get("ro.crypto.state", encrypted_state, "");
1362 if (strcmp(encrypted_state, "encrypted") ) {
1363 SLOGE("device not encrypted, aborting");
1364 return -2;
1365 }
1366
1367 if (!master_key_saved) {
1368 SLOGE("encrypted fs not yet mounted, aborting");
1369 return -1;
1370 }
1371
1372 if (!saved_mount_point) {
1373 SLOGE("encrypted fs failed to save mount point, aborting");
1374 return -1;
1375 }
1376
Ken Sumrall160b4d62013-04-22 12:15:39 -07001377 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001378 SLOGE("Error getting crypt footer and key\n");
1379 return -1;
1380 }
1381
1382 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1383 /* If the device has no password, then just say the password is valid */
1384 rc = 0;
1385 } else {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001386 decrypt_master_key_and_upgrade(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001387 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1388 /* They match, the password is correct */
1389 rc = 0;
1390 } else {
1391 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1392 sleep(1);
1393 rc = 1;
1394 }
1395 }
1396
1397 return rc;
1398}
1399
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001400/* Initialize a crypt_mnt_ftr structure. The keysize is
1401 * defaulted to 16 bytes, and the filesystem size to 0.
1402 * Presumably, at a minimum, the caller will update the
1403 * filesystem size and crypto_type_name after calling this function.
1404 */
1405static void cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
1406{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001407 off64_t off;
1408
1409 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001410 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001411 ftr->major_version = CURRENT_MAJOR_VERSION;
1412 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001413 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001414 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001415
Kenny Rootc4c70f12013-06-14 12:11:38 -07001416 ftr->kdf_type = KDF_SCRYPT;
1417 get_device_scrypt_params(ftr);
1418
Ken Sumrall160b4d62013-04-22 12:15:39 -07001419 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1420 if (get_crypt_ftr_info(NULL, &off) == 0) {
1421 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1422 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1423 ftr->persist_data_size;
1424 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001425}
1426
Ken Sumrall29d8da82011-05-18 17:20:07 -07001427static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001428{
1429 char cmdline[256];
1430 int rc = -1;
1431
Ken Sumrall29d8da82011-05-18 17:20:07 -07001432 if (type == EXT4_FS) {
1433 snprintf(cmdline, sizeof(cmdline), "/system/bin/make_ext4fs -a /data -l %lld %s",
1434 size * 512, crypto_blkdev);
1435 SLOGI("Making empty filesystem with command %s\n", cmdline);
1436 } else if (type== FAT_FS) {
1437 snprintf(cmdline, sizeof(cmdline), "/system/bin/newfs_msdos -F 32 -O android -c 8 -s %lld %s",
1438 size, crypto_blkdev);
1439 SLOGI("Making empty filesystem with command %s\n", cmdline);
1440 } else {
1441 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1442 return -1;
1443 }
1444
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001445 if (system(cmdline)) {
1446 SLOGE("Error creating empty filesystem on %s\n", crypto_blkdev);
1447 } else {
1448 SLOGD("Successfully created empty filesystem on %s\n", crypto_blkdev);
1449 rc = 0;
1450 }
1451
1452 return rc;
1453}
1454
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001455#define CRYPT_INPLACE_BUFSIZE 4096
1456#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / 512)
Ken Sumrall29d8da82011-05-18 17:20:07 -07001457static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev, off64_t size,
1458 off64_t *size_already_done, off64_t tot_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001459{
1460 int realfd, cryptofd;
1461 char *buf[CRYPT_INPLACE_BUFSIZE];
1462 int rc = -1;
1463 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001464 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001465 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001466
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001467 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
1468 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
1469 return -1;
1470 }
1471
1472 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
1473 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1474 close(realfd);
1475 return -1;
1476 }
1477
1478 /* This is pretty much a simple loop of reading 4K, and writing 4K.
1479 * The size passed in is the number of 512 byte sectors in the filesystem.
1480 * So compute the number of whole 4K blocks we should read/write,
1481 * and the remainder.
1482 */
1483 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
1484 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001485 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
1486 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001487
1488 SLOGE("Encrypting filesystem in place...");
1489
Ken Sumrall29d8da82011-05-18 17:20:07 -07001490 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001491 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001492 /* process the majority of the filesystem in blocks */
1493 for (i=0; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001494 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001495 if (new_pct > cur_pct) {
1496 char buf[8];
1497
1498 cur_pct = new_pct;
1499 snprintf(buf, sizeof(buf), "%lld", cur_pct);
1500 property_set("vold.encrypt_progress", buf);
1501 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001502 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1503 SLOGE("Error reading real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1504 goto errout;
1505 }
1506 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1507 SLOGE("Error writing crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1508 goto errout;
1509 }
1510 }
1511
1512 /* Do any remaining sectors */
1513 for (i=0; i<remainder; i++) {
1514 if (unix_read(realfd, buf, 512) <= 0) {
1515 SLOGE("Error reading rival sectors from real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1516 goto errout;
1517 }
1518 if (unix_write(cryptofd, buf, 512) <= 0) {
1519 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1520 goto errout;
1521 }
1522 }
1523
Ken Sumrall29d8da82011-05-18 17:20:07 -07001524 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001525 rc = 0;
1526
1527errout:
1528 close(realfd);
1529 close(cryptofd);
1530
1531 return rc;
1532}
1533
1534#define CRYPTO_ENABLE_WIPE 1
1535#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001536
1537#define FRAMEWORK_BOOT_WAIT 60
1538
Ken Sumrall29d8da82011-05-18 17:20:07 -07001539static inline int should_encrypt(struct volume_info *volume)
1540{
1541 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
1542 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
1543}
1544
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001545int cryptfs_enable(char *howarg, char *passwd)
1546{
1547 int how = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001548 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN], sd_crypto_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07001549 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001550 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07001551 int rc=-1, fd, i, ret;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001552 struct crypt_mnt_ftr crypt_ftr, sd_crypt_ftr;;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001553 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001554 char tmpfs_options[PROPERTY_VALUE_MAX];
1555 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001556 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07001557 char key_loc[PROPERTY_VALUE_MAX];
1558 char fuse_sdcard[PROPERTY_VALUE_MAX];
1559 char *sd_mnt_point;
1560 char sd_blk_dev[256] = { 0 };
1561 int num_vols;
1562 struct volume_info *vol_list = 0;
1563 off64_t cur_encryption_done=0, tot_encryption_size=0;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001564
1565 property_get("ro.crypto.state", encrypted_state, "");
1566 if (strcmp(encrypted_state, "unencrypted")) {
1567 SLOGE("Device is already running encrypted, aborting");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001568 goto error_unencrypted;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001569 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001570
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001571 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001572
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001573 if (!strcmp(howarg, "wipe")) {
1574 how = CRYPTO_ENABLE_WIPE;
1575 } else if (! strcmp(howarg, "inplace")) {
1576 how = CRYPTO_ENABLE_INPLACE;
1577 } else {
1578 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08001579 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001580 }
1581
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001582 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001583
Ken Sumrall3ed82362011-01-28 23:31:16 -08001584 /* Get the size of the real block device */
1585 fd = open(real_blkdev, O_RDONLY);
1586 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
1587 SLOGE("Cannot get size of block device %s\n", real_blkdev);
1588 goto error_unencrypted;
1589 }
1590 close(fd);
1591
1592 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001593 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001594 unsigned int fs_size_sec, max_fs_size_sec;
1595
1596 fs_size_sec = get_fs_size(real_blkdev);
1597 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1598
1599 if (fs_size_sec > max_fs_size_sec) {
1600 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
1601 goto error_unencrypted;
1602 }
1603 }
1604
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001605 /* Get a wakelock as this may take a while, and we don't want the
1606 * device to sleep on us. We'll grab a partial wakelock, and if the UI
1607 * wants to keep the screen on, it can grab a full wakelock.
1608 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001609 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001610 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
1611
Jeff Sharkey7382f812012-08-23 14:08:59 -07001612 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07001613 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07001614 if (!sd_mnt_point) {
1615 sd_mnt_point = getenv("EXTERNAL_STORAGE");
1616 }
1617 if (!sd_mnt_point) {
1618 sd_mnt_point = "/mnt/sdcard";
1619 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07001620
1621 num_vols=vold_getNumDirectVolumes();
1622 vol_list = malloc(sizeof(struct volume_info) * num_vols);
1623 vold_getDirectVolumeList(vol_list);
1624
1625 for (i=0; i<num_vols; i++) {
1626 if (should_encrypt(&vol_list[i])) {
1627 fd = open(vol_list[i].blk_dev, O_RDONLY);
1628 if ( (vol_list[i].size = get_blkdev_size(fd)) == 0) {
1629 SLOGE("Cannot get size of block device %s\n", vol_list[i].blk_dev);
1630 goto error_unencrypted;
1631 }
1632 close(fd);
1633
Ken Sumrall3b170052011-07-11 15:38:57 -07001634 ret=vold_disableVol(vol_list[i].label);
Ken Sumrall319b1042011-06-14 14:01:55 -07001635 if ((ret < 0) && (ret != UNMOUNT_NOT_MOUNTED_ERR)) {
1636 /* -2 is returned when the device exists but is not currently mounted.
1637 * ignore the error and continue. */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001638 SLOGE("Failed to unmount volume %s\n", vol_list[i].label);
1639 goto error_unencrypted;
1640 }
1641 }
1642 }
1643
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001644 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001645 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001646 */
1647 property_set("vold.decrypt", "trigger_shutdown_framework");
1648 SLOGD("Just asked init to shut down class main\n");
1649
Ken Sumrall425524d2012-06-14 20:55:28 -07001650 if (vold_unmountAllAsecs()) {
1651 /* Just report the error. If any are left mounted,
1652 * umounting /data below will fail and handle the error.
1653 */
1654 SLOGE("Error unmounting internal asecs");
1655 }
1656
Ken Sumrall29d8da82011-05-18 17:20:07 -07001657 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
1658 if (!strcmp(fuse_sdcard, "true")) {
1659 /* This is a device using the fuse layer to emulate the sdcard semantics
1660 * on top of the userdata partition. vold does not manage it, it is managed
1661 * by the sdcard service. The sdcard service was killed by the property trigger
1662 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
1663 * unlike the case for vold managed devices above.
1664 */
1665 if (wait_and_unmount(sd_mnt_point)) {
1666 goto error_shutting_down;
1667 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001668 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001669
1670 /* Now unmount the /data partition. */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001671 if (wait_and_unmount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001672 goto error_shutting_down;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001673 }
1674
1675 /* Do extra work for a better UX when doing the long inplace encryption */
1676 if (how == CRYPTO_ENABLE_INPLACE) {
1677 /* Now that /data is unmounted, we need to mount a tmpfs
1678 * /data, set a property saying we're doing inplace encryption,
1679 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001680 */
Ken Sumralle5032c42012-04-01 23:58:44 -07001681 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001682 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001683 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001684 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08001685 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001686
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001687 /* restart the framework. */
1688 /* Create necessary paths on /data */
1689 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001690 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001691 }
1692
Ken Sumrall92736ef2012-10-17 20:57:14 -07001693 /* Ugh, shutting down the framework is not synchronous, so until it
1694 * can be fixed, this horrible hack will wait a moment for it all to
1695 * shut down before proceeding. Without it, some devices cannot
1696 * restart the graphics services.
1697 */
1698 sleep(2);
1699
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001700 /* startup service classes main and late_start */
1701 property_set("vold.decrypt", "trigger_restart_min_framework");
1702 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001703
Ken Sumrall7df84122011-01-18 14:04:08 -08001704 /* OK, the framework is restarted and will soon be showing a
1705 * progress bar. Time to setup an encrypted mapping, and
1706 * either write a new filesystem, or encrypt in place updating
1707 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001708 */
1709 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001710
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001711 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001712 /* Initialize a crypt_mnt_ftr for the partition */
1713 cryptfs_init_crypt_mnt_ftr(&crypt_ftr);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001714
Ken Sumrall29d8da82011-05-18 17:20:07 -07001715 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
1716 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1717 } else {
1718 crypt_ftr.fs_size = nr_sec;
1719 }
Ken Sumralld33d4172011-02-01 00:49:13 -08001720 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001721 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
1722
1723 /* Make an encrypted master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001724 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001725 SLOGE("Cannot create encrypted master key\n");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001726 goto error_unencrypted;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001727 }
1728
1729 /* Write the key to the end of the partition */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001730 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001731
Ken Sumrall160b4d62013-04-22 12:15:39 -07001732 /* If any persistent data has been remembered, save it.
1733 * If none, create a valid empty table and save that.
1734 */
1735 if (!persist_data) {
1736 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
1737 if (pdata) {
1738 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
1739 persist_data = pdata;
1740 }
1741 }
1742 if (persist_data) {
1743 save_persistent_data();
1744 }
1745
Kenny Rootc4c70f12013-06-14 12:11:38 -07001746 decrypt_master_key_and_upgrade(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001747 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
1748 "userdata");
1749
Ken Sumrall128626f2011-06-28 18:45:14 -07001750 /* The size of the userdata partition, and add in the vold volumes below */
1751 tot_encryption_size = crypt_ftr.fs_size;
1752
Ken Sumrall29d8da82011-05-18 17:20:07 -07001753 /* setup crypto mapping for all encryptable volumes handled by vold */
1754 for (i=0; i<num_vols; i++) {
1755 if (should_encrypt(&vol_list[i])) {
1756 vol_list[i].crypt_ftr = crypt_ftr; /* gotta love struct assign */
1757 vol_list[i].crypt_ftr.fs_size = vol_list[i].size;
1758 create_crypto_blk_dev(&vol_list[i].crypt_ftr, decrypted_master_key,
1759 vol_list[i].blk_dev, vol_list[i].crypto_blkdev,
1760 vol_list[i].label);
Ken Sumrall128626f2011-06-28 18:45:14 -07001761 tot_encryption_size += vol_list[i].size;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001762 }
1763 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001764
1765 if (how == CRYPTO_ENABLE_WIPE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001766 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr.fs_size, EXT4_FS);
1767 /* Encrypt all encryptable volumes handled by vold */
1768 if (!rc) {
1769 for (i=0; i<num_vols; i++) {
1770 if (should_encrypt(&vol_list[i])) {
1771 rc = cryptfs_enable_wipe(vol_list[i].crypto_blkdev,
1772 vol_list[i].crypt_ftr.fs_size, FAT_FS);
1773 }
1774 }
1775 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001776 } else if (how == CRYPTO_ENABLE_INPLACE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001777 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr.fs_size,
1778 &cur_encryption_done, tot_encryption_size);
1779 /* Encrypt all encryptable volumes handled by vold */
1780 if (!rc) {
1781 for (i=0; i<num_vols; i++) {
1782 if (should_encrypt(&vol_list[i])) {
1783 rc = cryptfs_enable_inplace(vol_list[i].crypto_blkdev,
1784 vol_list[i].blk_dev,
1785 vol_list[i].crypt_ftr.fs_size,
1786 &cur_encryption_done, tot_encryption_size);
1787 }
1788 }
1789 }
1790 if (!rc) {
1791 /* The inplace routine never actually sets the progress to 100%
1792 * due to the round down nature of integer division, so set it here */
1793 property_set("vold.encrypt_progress", "100");
1794 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001795 } else {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001796 /* Shouldn't happen */
1797 SLOGE("cryptfs_enable: internal error, unknown option\n");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001798 goto error_unencrypted;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001799 }
1800
1801 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001802 delete_crypto_blk_dev("userdata");
1803 for (i=0; i<num_vols; i++) {
1804 if (should_encrypt(&vol_list[i])) {
1805 delete_crypto_blk_dev(vol_list[i].label);
1806 }
1807 }
1808
1809 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001810
1811 if (! rc) {
1812 /* Success */
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001813
Ken Sumralld33d4172011-02-01 00:49:13 -08001814 /* Clear the encryption in progres flag in the footer */
1815 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001816 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08001817
Ken Sumrall29d8da82011-05-18 17:20:07 -07001818 sleep(2); /* Give the UI a chance to show 100% progress */
Ken Sumralladfba362013-06-04 16:37:52 -07001819 cryptfs_reboot(0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001820 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001821 char value[PROPERTY_VALUE_MAX];
1822
Ken Sumrall319369a2012-06-27 16:30:18 -07001823 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001824 if (!strcmp(value, "1")) {
1825 /* wipe data if encryption failed */
1826 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
1827 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07001828 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001829 if (fd >= 0) {
1830 write(fd, "--wipe_data", strlen("--wipe_data") + 1);
1831 close(fd);
1832 } else {
1833 SLOGE("could not open /cache/recovery/command\n");
1834 }
Ken Sumralladfba362013-06-04 16:37:52 -07001835 cryptfs_reboot(1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001836 } else {
1837 /* set property to trigger dialog */
1838 property_set("vold.encrypt_progress", "error_partially_encrypted");
1839 release_wake_lock(lockid);
1840 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001841 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001842 }
1843
Ken Sumrall3ed82362011-01-28 23:31:16 -08001844 /* hrm, the encrypt step claims success, but the reboot failed.
1845 * This should not happen.
1846 * Set the property and return. Hope the framework can deal with it.
1847 */
1848 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001849 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001850 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08001851
1852error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07001853 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001854 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001855 if (lockid[0]) {
1856 release_wake_lock(lockid);
1857 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001858 return -1;
1859
1860error_shutting_down:
1861 /* we failed, and have not encrypted anthing, so the users's data is still intact,
1862 * but the framework is stopped and not restarted to show the error, so it's up to
1863 * vold to restart the system.
1864 */
1865 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Ken Sumralladfba362013-06-04 16:37:52 -07001866 cryptfs_reboot(0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001867
1868 /* shouldn't get here */
1869 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001870 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001871 if (lockid[0]) {
1872 release_wake_lock(lockid);
1873 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001874 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001875}
1876
Jason parks70a4b3f2011-01-28 10:10:47 -06001877int cryptfs_changepw(char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001878{
1879 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001880 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001881
1882 /* This is only allowed after we've successfully decrypted the master key */
Jason parks70a4b3f2011-01-28 10:10:47 -06001883 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001884 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001885 return -1;
1886 }
1887
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001888 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001889 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall57b63e62011-01-17 18:29:19 -08001890 SLOGE("Error getting crypt footer and key");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001891 return -1;
1892 }
1893
Kenny Rootc4c70f12013-06-14 12:11:38 -07001894 encrypt_master_key(newpw, crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001895
Jason parks70a4b3f2011-01-28 10:10:47 -06001896 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001897 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001898
1899 return 0;
1900}
Ken Sumrall160b4d62013-04-22 12:15:39 -07001901
1902static int persist_get_key(char *fieldname, char *value)
1903{
1904 unsigned int i;
1905
1906 if (persist_data == NULL) {
1907 return -1;
1908 }
1909 for (i = 0; i < persist_data->persist_valid_entries; i++) {
1910 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
1911 /* We found it! */
1912 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
1913 return 0;
1914 }
1915 }
1916
1917 return -1;
1918}
1919
1920static int persist_set_key(char *fieldname, char *value, int encrypted)
1921{
1922 unsigned int i;
1923 unsigned int num;
1924 struct crypt_mnt_ftr crypt_ftr;
1925 unsigned int max_persistent_entries;
1926 unsigned int dsize;
1927
1928 if (persist_data == NULL) {
1929 return -1;
1930 }
1931
1932 /* If encrypted, use the values from the crypt_ftr, otherwise
1933 * use the values for the current spec.
1934 */
1935 if (encrypted) {
1936 if(get_crypt_ftr_and_key(&crypt_ftr)) {
1937 return -1;
1938 }
1939 dsize = crypt_ftr.persist_data_size;
1940 } else {
1941 dsize = CRYPT_PERSIST_DATA_SIZE;
1942 }
1943 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
1944 sizeof(struct crypt_persist_entry);
1945
1946 num = persist_data->persist_valid_entries;
1947
1948 for (i = 0; i < num; i++) {
1949 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
1950 /* We found an existing entry, update it! */
1951 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
1952 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
1953 return 0;
1954 }
1955 }
1956
1957 /* We didn't find it, add it to the end, if there is room */
1958 if (persist_data->persist_valid_entries < max_persistent_entries) {
1959 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
1960 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
1961 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
1962 persist_data->persist_valid_entries++;
1963 return 0;
1964 }
1965
1966 return -1;
1967}
1968
1969/* Return the value of the specified field. */
1970int cryptfs_getfield(char *fieldname, char *value, int len)
1971{
1972 char temp_value[PROPERTY_VALUE_MAX];
1973 char real_blkdev[MAXPATHLEN];
1974 /* 0 is success, 1 is not encrypted,
1975 * -1 is value not set, -2 is any other error
1976 */
1977 int rc = -2;
1978
1979 if (persist_data == NULL) {
1980 load_persistent_data();
1981 if (persist_data == NULL) {
1982 SLOGE("Getfield error, cannot load persistent data");
1983 goto out;
1984 }
1985 }
1986
1987 if (!persist_get_key(fieldname, temp_value)) {
1988 /* We found it, copy it to the caller's buffer and return */
1989 strlcpy(value, temp_value, len);
1990 rc = 0;
1991 } else {
1992 /* Sadness, it's not there. Return the error */
1993 rc = -1;
1994 }
1995
1996out:
1997 return rc;
1998}
1999
2000/* Set the value of the specified field. */
2001int cryptfs_setfield(char *fieldname, char *value)
2002{
2003 struct crypt_persist_data stored_pdata;
2004 struct crypt_persist_data *pdata_p;
2005 struct crypt_mnt_ftr crypt_ftr;
2006 char encrypted_state[PROPERTY_VALUE_MAX];
2007 /* 0 is success, -1 is an error */
2008 int rc = -1;
2009 int encrypted = 0;
2010
2011 if (persist_data == NULL) {
2012 load_persistent_data();
2013 if (persist_data == NULL) {
2014 SLOGE("Setfield error, cannot load persistent data");
2015 goto out;
2016 }
2017 }
2018
2019 property_get("ro.crypto.state", encrypted_state, "");
2020 if (!strcmp(encrypted_state, "encrypted") ) {
2021 encrypted = 1;
2022 }
2023
2024 if (persist_set_key(fieldname, value, encrypted)) {
2025 goto out;
2026 }
2027
2028 /* If we are running encrypted, save the persistent data now */
2029 if (encrypted) {
2030 if (save_persistent_data()) {
2031 SLOGE("Setfield error, cannot save persistent data");
2032 goto out;
2033 }
2034 }
2035
2036 rc = 0;
2037
2038out:
2039 return rc;
2040}