blob: e5459199f7fa0f60930dd045103c5b5738a78c05 [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
23#include <sys/types.h>
Ken Sumralle550f782013-08-20 13:48:23 -070024#include <sys/wait.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080025#include <sys/stat.h>
26#include <fcntl.h>
27#include <unistd.h>
28#include <stdio.h>
29#include <sys/ioctl.h>
30#include <linux/dm-ioctl.h>
31#include <libgen.h>
32#include <stdlib.h>
33#include <sys/param.h>
34#include <string.h>
35#include <sys/mount.h>
36#include <openssl/evp.h>
Ken Sumrall8ddbe402011-01-17 15:26:29 -080037#include <openssl/sha.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080038#include <errno.h>
Ken Sumrall3ed82362011-01-28 23:31:16 -080039#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070040#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070041#include <fs_mgr.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080042#include "cryptfs.h"
43#define LOG_TAG "Cryptfs"
44#include "cutils/log.h"
45#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070046#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080047#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070048#include <logwrap/logwrap.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070049#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070050#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070051#include "crypto_scrypt.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080052
Mark Salyzyn5eecc442014-02-12 14:16:14 -080053#define UNUSED __attribute__((unused))
54
Ken Sumrall8f869aa2010-12-03 03:47:09 -080055#define DM_CRYPT_BUF_SIZE 4096
Ken Sumrall8ddbe402011-01-17 15:26:29 -080056#define DATA_MNT_POINT "/data"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080057
Jason parks70a4b3f2011-01-28 10:10:47 -060058#define HASH_COUNT 2000
59#define KEY_LEN_BYTES 16
60#define IV_LEN_BYTES 16
61
Ken Sumrall29d8da82011-05-18 17:20:07 -070062#define KEY_IN_FOOTER "footer"
63
64#define EXT4_FS 1
65#define FAT_FS 2
66
Ken Sumralle919efe2012-09-29 17:07:41 -070067#define TABLE_LOAD_RETRIES 10
68
Ken Sumrall8f869aa2010-12-03 03:47:09 -080069char *me = "cryptfs";
70
Jason parks70a4b3f2011-01-28 10:10:47 -060071static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070072static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060073static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -070074static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -080075
76extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -080077
Ken Sumralladfba362013-06-04 16:37:52 -070078static void cryptfs_reboot(int recovery)
79{
80 if (recovery) {
81 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
82 } else {
83 property_set(ANDROID_RB_PROPERTY, "reboot");
84 }
85 sleep(20);
86
87 /* Shouldn't get here, reboot should happen before sleep times out */
88 return;
89}
90
Ken Sumrall8f869aa2010-12-03 03:47:09 -080091static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
92{
93 memset(io, 0, dataSize);
94 io->data_size = dataSize;
95 io->data_start = sizeof(struct dm_ioctl);
96 io->version[0] = 4;
97 io->version[1] = 0;
98 io->version[2] = 0;
99 io->flags = flags;
100 if (name) {
101 strncpy(io->name, name, sizeof(io->name));
102 }
103}
104
Kenny Rootc4c70f12013-06-14 12:11:38 -0700105/**
106 * Gets the default device scrypt parameters for key derivation time tuning.
107 * The parameters should lead to about one second derivation time for the
108 * given device.
109 */
110static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
111 const int default_params[] = SCRYPT_DEFAULTS;
112 int params[] = SCRYPT_DEFAULTS;
113 char paramstr[PROPERTY_VALUE_MAX];
114 char *token;
115 char *saveptr;
116 int i;
117
118 property_get(SCRYPT_PROP, paramstr, "");
119 if (paramstr[0] != '\0') {
120 /*
121 * The token we're looking for should be three integers separated by
122 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
123 */
Kenny Root2947e342013-08-14 15:54:49 -0700124 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
125 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700126 i++, token = strtok_r(NULL, ":", &saveptr)) {
127 char *endptr;
128 params[i] = strtol(token, &endptr, 10);
129
130 /*
131 * Check that there was a valid number and it's 8-bit. If not,
132 * break out and the end check will take the default values.
133 */
134 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
135 break;
136 }
137 }
138
139 /*
140 * If there were not enough tokens or a token was malformed (not an
141 * integer), it will end up here and the default parameters can be
142 * taken.
143 */
144 if ((i != 3) || (token != NULL)) {
145 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
146 memcpy(params, default_params, sizeof(params));
147 }
148 }
149
150 ftr->N_factor = params[0];
151 ftr->r_factor = params[1];
152 ftr->p_factor = params[2];
153}
154
Ken Sumrall3ed82362011-01-28 23:31:16 -0800155static unsigned int get_fs_size(char *dev)
156{
157 int fd, block_size;
158 struct ext4_super_block sb;
159 off64_t len;
160
161 if ((fd = open(dev, O_RDONLY)) < 0) {
162 SLOGE("Cannot open device to get filesystem size ");
163 return 0;
164 }
165
166 if (lseek64(fd, 1024, SEEK_SET) < 0) {
167 SLOGE("Cannot seek to superblock");
168 return 0;
169 }
170
171 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
172 SLOGE("Cannot read superblock");
173 return 0;
174 }
175
176 close(fd);
177
178 block_size = 1024 << sb.s_log_block_size;
179 /* compute length in bytes */
180 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
181
182 /* return length in sectors */
183 return (unsigned int) (len / 512);
184}
185
Ken Sumrall160b4d62013-04-22 12:15:39 -0700186static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
187{
188 static int cached_data = 0;
189 static off64_t cached_off = 0;
190 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
191 int fd;
192 char key_loc[PROPERTY_VALUE_MAX];
193 char real_blkdev[PROPERTY_VALUE_MAX];
194 unsigned int nr_sec;
195 int rc = -1;
196
197 if (!cached_data) {
198 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
199
200 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
201 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
202 SLOGE("Cannot open real block device %s\n", real_blkdev);
203 return -1;
204 }
205
206 if ((nr_sec = get_blkdev_size(fd))) {
207 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
208 * encryption info footer and key, and plenty of bytes to spare for future
209 * growth.
210 */
211 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
212 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
213 cached_data = 1;
214 } else {
215 SLOGE("Cannot get size of block device %s\n", real_blkdev);
216 }
217 close(fd);
218 } else {
219 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
220 cached_off = 0;
221 cached_data = 1;
222 }
223 }
224
225 if (cached_data) {
226 if (metadata_fname) {
227 *metadata_fname = cached_metadata_fname;
228 }
229 if (off) {
230 *off = cached_off;
231 }
232 rc = 0;
233 }
234
235 return rc;
236}
237
Ken Sumralle8744072011-01-18 22:01:55 -0800238/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800239 * update the failed mount count but not change the key.
240 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700241static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800242{
243 int fd;
244 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700245 /* starting_off is set to the SEEK_SET offset
246 * where the crypto structure starts
247 */
248 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800249 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700250 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700251 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800252
Ken Sumrall160b4d62013-04-22 12:15:39 -0700253 if (get_crypt_ftr_info(&fname, &starting_off)) {
254 SLOGE("Unable to get crypt_ftr_info\n");
255 return -1;
256 }
257 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700258 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700259 return -1;
260 }
Ken Sumralle550f782013-08-20 13:48:23 -0700261 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
262 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700263 return -1;
264 }
265
266 /* Seek to the start of the crypt footer */
267 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
268 SLOGE("Cannot seek to real block device footer\n");
269 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800270 }
271
272 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
273 SLOGE("Cannot write real block device footer\n");
274 goto errout;
275 }
276
Ken Sumrall3be890f2011-09-14 16:53:46 -0700277 fstat(fd, &statbuf);
278 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700279 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700280 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800281 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800282 goto errout;
283 }
284 }
285
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800286 /* Success! */
287 rc = 0;
288
289errout:
290 close(fd);
291 return rc;
292
293}
294
Ken Sumrall160b4d62013-04-22 12:15:39 -0700295static inline int unix_read(int fd, void* buff, int len)
296{
297 return TEMP_FAILURE_RETRY(read(fd, buff, len));
298}
299
300static inline int unix_write(int fd, const void* buff, int len)
301{
302 return TEMP_FAILURE_RETRY(write(fd, buff, len));
303}
304
305static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
306{
307 memset(pdata, 0, len);
308 pdata->persist_magic = PERSIST_DATA_MAGIC;
309 pdata->persist_valid_entries = 0;
310}
311
312/* A routine to update the passed in crypt_ftr to the lastest version.
313 * fd is open read/write on the device that holds the crypto footer and persistent
314 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
315 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
316 */
317static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
318{
Kenny Root7434b312013-06-14 11:29:53 -0700319 int orig_major = crypt_ftr->major_version;
320 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700321
Kenny Root7434b312013-06-14 11:29:53 -0700322 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
323 struct crypt_persist_data *pdata;
324 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700325
Kenny Rootc4c70f12013-06-14 12:11:38 -0700326 SLOGW("upgrading crypto footer to 1.1");
327
Kenny Root7434b312013-06-14 11:29:53 -0700328 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
329 if (pdata == NULL) {
330 SLOGE("Cannot allocate persisent data\n");
331 return;
332 }
333 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
334
335 /* Need to initialize the persistent data area */
336 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
337 SLOGE("Cannot seek to persisent data offset\n");
338 return;
339 }
340 /* Write all zeros to the first copy, making it invalid */
341 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
342
343 /* Write a valid but empty structure to the second copy */
344 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
345 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
346
347 /* Update the footer */
348 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
349 crypt_ftr->persist_data_offset[0] = pdata_offset;
350 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
351 crypt_ftr->minor_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700352 }
353
Kenny Rootc4c70f12013-06-14 12:11:38 -0700354 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version)) {
355 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800356 /* But keep the old kdf_type.
357 * It will get updated later to KDF_SCRYPT after the password has been verified.
358 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700359 crypt_ftr->kdf_type = KDF_PBKDF2;
360 get_device_scrypt_params(crypt_ftr);
361 crypt_ftr->minor_version = 2;
362 }
363
Kenny Root7434b312013-06-14 11:29:53 -0700364 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
365 if (lseek64(fd, offset, SEEK_SET) == -1) {
366 SLOGE("Cannot seek to crypt footer\n");
367 return;
368 }
369 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700370 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700371}
372
373
374static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800375{
376 int fd;
377 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700378 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800379 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700380 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700381 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800382
Ken Sumrall160b4d62013-04-22 12:15:39 -0700383 if (get_crypt_ftr_info(&fname, &starting_off)) {
384 SLOGE("Unable to get crypt_ftr_info\n");
385 return -1;
386 }
387 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700388 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700389 return -1;
390 }
391 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700392 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700393 return -1;
394 }
395
396 /* Make sure it's 16 Kbytes in length */
397 fstat(fd, &statbuf);
398 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
399 SLOGE("footer file %s is not the expected size!\n", fname);
400 goto errout;
401 }
402
403 /* Seek to the start of the crypt footer */
404 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
405 SLOGE("Cannot seek to real block device footer\n");
406 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800407 }
408
409 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
410 SLOGE("Cannot read real block device footer\n");
411 goto errout;
412 }
413
414 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700415 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800416 goto errout;
417 }
418
Kenny Rootc96a5f82013-06-14 12:08:28 -0700419 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
420 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
421 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800422 goto errout;
423 }
424
Kenny Rootc96a5f82013-06-14 12:08:28 -0700425 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
426 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
427 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800428 }
429
Ken Sumrall160b4d62013-04-22 12:15:39 -0700430 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
431 * copy on disk before returning.
432 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700433 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700434 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800435 }
436
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800437 /* Success! */
438 rc = 0;
439
440errout:
441 close(fd);
442 return rc;
443}
444
Ken Sumrall160b4d62013-04-22 12:15:39 -0700445static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
446{
447 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
448 crypt_ftr->persist_data_offset[1]) {
449 SLOGE("Crypt_ftr persist data regions overlap");
450 return -1;
451 }
452
453 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
454 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
455 return -1;
456 }
457
458 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
459 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
460 CRYPT_FOOTER_OFFSET) {
461 SLOGE("Persistent data extends past crypto footer");
462 return -1;
463 }
464
465 return 0;
466}
467
468static int load_persistent_data(void)
469{
470 struct crypt_mnt_ftr crypt_ftr;
471 struct crypt_persist_data *pdata = NULL;
472 char encrypted_state[PROPERTY_VALUE_MAX];
473 char *fname;
474 int found = 0;
475 int fd;
476 int ret;
477 int i;
478
479 if (persist_data) {
480 /* Nothing to do, we've already loaded or initialized it */
481 return 0;
482 }
483
484
485 /* If not encrypted, just allocate an empty table and initialize it */
486 property_get("ro.crypto.state", encrypted_state, "");
487 if (strcmp(encrypted_state, "encrypted") ) {
488 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
489 if (pdata) {
490 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
491 persist_data = pdata;
492 return 0;
493 }
494 return -1;
495 }
496
497 if(get_crypt_ftr_and_key(&crypt_ftr)) {
498 return -1;
499 }
500
501 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
502 SLOGE("Crypt_ftr version doesn't support persistent data");
503 return -1;
504 }
505
506 if (get_crypt_ftr_info(&fname, NULL)) {
507 return -1;
508 }
509
510 ret = validate_persistent_data_storage(&crypt_ftr);
511 if (ret) {
512 return -1;
513 }
514
515 fd = open(fname, O_RDONLY);
516 if (fd < 0) {
517 SLOGE("Cannot open %s metadata file", fname);
518 return -1;
519 }
520
521 if (persist_data == NULL) {
522 pdata = malloc(crypt_ftr.persist_data_size);
523 if (pdata == NULL) {
524 SLOGE("Cannot allocate memory for persistent data");
525 goto err;
526 }
527 }
528
529 for (i = 0; i < 2; i++) {
530 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
531 SLOGE("Cannot seek to read persistent data on %s", fname);
532 goto err2;
533 }
534 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
535 SLOGE("Error reading persistent data on iteration %d", i);
536 goto err2;
537 }
538 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
539 found = 1;
540 break;
541 }
542 }
543
544 if (!found) {
545 SLOGI("Could not find valid persistent data, creating");
546 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
547 }
548
549 /* Success */
550 persist_data = pdata;
551 close(fd);
552 return 0;
553
554err2:
555 free(pdata);
556
557err:
558 close(fd);
559 return -1;
560}
561
562static int save_persistent_data(void)
563{
564 struct crypt_mnt_ftr crypt_ftr;
565 struct crypt_persist_data *pdata;
566 char *fname;
567 off64_t write_offset;
568 off64_t erase_offset;
569 int found = 0;
570 int fd;
571 int ret;
572
573 if (persist_data == NULL) {
574 SLOGE("No persistent data to save");
575 return -1;
576 }
577
578 if(get_crypt_ftr_and_key(&crypt_ftr)) {
579 return -1;
580 }
581
582 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
583 SLOGE("Crypt_ftr version doesn't support persistent data");
584 return -1;
585 }
586
587 ret = validate_persistent_data_storage(&crypt_ftr);
588 if (ret) {
589 return -1;
590 }
591
592 if (get_crypt_ftr_info(&fname, NULL)) {
593 return -1;
594 }
595
596 fd = open(fname, O_RDWR);
597 if (fd < 0) {
598 SLOGE("Cannot open %s metadata file", fname);
599 return -1;
600 }
601
602 pdata = malloc(crypt_ftr.persist_data_size);
603 if (pdata == NULL) {
604 SLOGE("Cannot allocate persistant data");
605 goto err;
606 }
607
608 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
609 SLOGE("Cannot seek to read persistent data on %s", fname);
610 goto err2;
611 }
612
613 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
614 SLOGE("Error reading persistent data before save");
615 goto err2;
616 }
617
618 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
619 /* The first copy is the curent valid copy, so write to
620 * the second copy and erase this one */
621 write_offset = crypt_ftr.persist_data_offset[1];
622 erase_offset = crypt_ftr.persist_data_offset[0];
623 } else {
624 /* The second copy must be the valid copy, so write to
625 * the first copy, and erase the second */
626 write_offset = crypt_ftr.persist_data_offset[0];
627 erase_offset = crypt_ftr.persist_data_offset[1];
628 }
629
630 /* Write the new copy first, if successful, then erase the old copy */
631 if (lseek(fd, write_offset, SEEK_SET) < 0) {
632 SLOGE("Cannot seek to write persistent data");
633 goto err2;
634 }
635 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
636 (int) crypt_ftr.persist_data_size) {
637 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
638 SLOGE("Cannot seek to erase previous persistent data");
639 goto err2;
640 }
641 fsync(fd);
642 memset(pdata, 0, crypt_ftr.persist_data_size);
643 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
644 (int) crypt_ftr.persist_data_size) {
645 SLOGE("Cannot write to erase previous persistent data");
646 goto err2;
647 }
648 fsync(fd);
649 } else {
650 SLOGE("Cannot write to save persistent data");
651 goto err2;
652 }
653
654 /* Success */
655 free(pdata);
656 close(fd);
657 return 0;
658
659err2:
660 free(pdata);
661err:
662 close(fd);
663 return -1;
664}
665
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800666/* Convert a binary key of specified length into an ascii hex string equivalent,
667 * without the leading 0x and with null termination
668 */
669void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
670 char *master_key_ascii)
671{
672 unsigned int i, a;
673 unsigned char nibble;
674
675 for (i=0, a=0; i<keysize; i++, a+=2) {
676 /* For each byte, write out two ascii hex digits */
677 nibble = (master_key[i] >> 4) & 0xf;
678 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
679
680 nibble = master_key[i] & 0xf;
681 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
682 }
683
684 /* Add the null termination */
685 master_key_ascii[a] = '\0';
686
687}
688
Ken Sumralldb5e0262013-02-05 17:39:48 -0800689static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
690 char *real_blk_name, const char *name, int fd,
691 char *extra_params)
692{
693 char buffer[DM_CRYPT_BUF_SIZE];
694 struct dm_ioctl *io;
695 struct dm_target_spec *tgt;
696 char *crypt_params;
697 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
698 int i;
699
700 io = (struct dm_ioctl *) buffer;
701
702 /* Load the mapping table for this device */
703 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
704
705 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
706 io->target_count = 1;
707 tgt->status = 0;
708 tgt->sector_start = 0;
709 tgt->length = crypt_ftr->fs_size;
710 strcpy(tgt->target_type, "crypt");
711
712 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
713 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
714 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
715 master_key_ascii, real_blk_name, extra_params);
716 crypt_params += strlen(crypt_params) + 1;
717 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
718 tgt->next = crypt_params - buffer;
719
720 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
721 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
722 break;
723 }
724 usleep(500000);
725 }
726
727 if (i == TABLE_LOAD_RETRIES) {
728 /* We failed to load the table, return an error */
729 return -1;
730 } else {
731 return i + 1;
732 }
733}
734
735
736static int get_dm_crypt_version(int fd, const char *name, int *version)
737{
738 char buffer[DM_CRYPT_BUF_SIZE];
739 struct dm_ioctl *io;
740 struct dm_target_versions *v;
741 int i;
742
743 io = (struct dm_ioctl *) buffer;
744
745 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
746
747 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
748 return -1;
749 }
750
751 /* Iterate over the returned versions, looking for name of "crypt".
752 * When found, get and return the version.
753 */
754 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
755 while (v->next) {
756 if (! strcmp(v->name, "crypt")) {
757 /* We found the crypt driver, return the version, and get out */
758 version[0] = v->version[0];
759 version[1] = v->version[1];
760 version[2] = v->version[2];
761 return 0;
762 }
763 v = (struct dm_target_versions *)(((char *)v) + v->next);
764 }
765
766 return -1;
767}
768
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800769static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -0700770 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800771{
772 char buffer[DM_CRYPT_BUF_SIZE];
773 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
774 char *crypt_params;
775 struct dm_ioctl *io;
776 struct dm_target_spec *tgt;
777 unsigned int minor;
778 int fd;
Ken Sumralle919efe2012-09-29 17:07:41 -0700779 int i;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800780 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800781 int version[3];
782 char *extra_params;
783 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800784
785 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
786 SLOGE("Cannot open device-mapper\n");
787 goto errout;
788 }
789
790 io = (struct dm_ioctl *) buffer;
791
792 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
793 if (ioctl(fd, DM_DEV_CREATE, io)) {
794 SLOGE("Cannot create dm-crypt device\n");
795 goto errout;
796 }
797
798 /* Get the device status, in particular, the name of it's device file */
799 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
800 if (ioctl(fd, DM_DEV_STATUS, io)) {
801 SLOGE("Cannot retrieve dm-crypt device status\n");
802 goto errout;
803 }
804 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
805 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
806
Ken Sumralldb5e0262013-02-05 17:39:48 -0800807 extra_params = "";
808 if (! get_dm_crypt_version(fd, name, version)) {
809 /* Support for allow_discards was added in version 1.11.0 */
810 if ((version[0] >= 2) ||
811 ((version[0] == 1) && (version[1] >= 11))) {
812 extra_params = "1 allow_discards";
813 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
814 }
Ken Sumralle919efe2012-09-29 17:07:41 -0700815 }
816
Ken Sumralldb5e0262013-02-05 17:39:48 -0800817 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
818 fd, extra_params);
819 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800820 SLOGE("Cannot load dm-crypt mapping table.\n");
821 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800822 } else if (load_count > 1) {
823 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800824 }
825
826 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -0800827 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800828
829 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
830 SLOGE("Cannot resume the dm-crypt device\n");
831 goto errout;
832 }
833
834 /* We made it here with no errors. Woot! */
835 retval = 0;
836
837errout:
838 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
839
840 return retval;
841}
842
Ken Sumrall29d8da82011-05-18 17:20:07 -0700843static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800844{
845 int fd;
846 char buffer[DM_CRYPT_BUF_SIZE];
847 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800848 int retval = -1;
849
850 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
851 SLOGE("Cannot open device-mapper\n");
852 goto errout;
853 }
854
855 io = (struct dm_ioctl *) buffer;
856
857 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
858 if (ioctl(fd, DM_DEV_REMOVE, io)) {
859 SLOGE("Cannot remove dm-crypt device\n");
860 goto errout;
861 }
862
863 /* We made it here with no errors. Woot! */
864 retval = 0;
865
866errout:
867 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
868
869 return retval;
870
871}
872
Mark Salyzyn5eecc442014-02-12 14:16:14 -0800873static void pbkdf2(char *passwd, unsigned char *salt, unsigned char *ikey, void *params UNUSED) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800874 /* Turn the password into a key and IV that can decrypt the master key */
Ken Sumralle8744072011-01-18 22:01:55 -0800875 PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800876 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800877}
878
Kenny Rootc4c70f12013-06-14 12:11:38 -0700879static void scrypt(char *passwd, unsigned char *salt, unsigned char *ikey, void *params) {
880 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
881
882 int N = 1 << ftr->N_factor;
883 int r = 1 << ftr->r_factor;
884 int p = 1 << ftr->p_factor;
885
886 /* Turn the password into a key and IV that can decrypt the master key */
887 crypto_scrypt((unsigned char *) passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
888 KEY_LEN_BYTES + IV_LEN_BYTES);
889}
890
Ken Sumralle8744072011-01-18 22:01:55 -0800891static int encrypt_master_key(char *passwd, unsigned char *salt,
892 unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700893 unsigned char *encrypted_master_key,
894 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800895{
896 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
897 EVP_CIPHER_CTX e_ctx;
898 int encrypted_len, final_len;
899
900 /* Turn the password into a key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700901 get_device_scrypt_params(crypt_ftr);
902 scrypt(passwd, salt, ikey, crypt_ftr);
903
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800904 /* Initialize the decryption engine */
905 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
906 SLOGE("EVP_EncryptInit failed\n");
907 return -1;
908 }
909 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800910
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800911 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800912 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
913 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800914 SLOGE("EVP_EncryptUpdate failed\n");
915 return -1;
916 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800917 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800918 SLOGE("EVP_EncryptFinal failed\n");
919 return -1;
920 }
921
922 if (encrypted_len + final_len != KEY_LEN_BYTES) {
923 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
924 return -1;
925 } else {
926 return 0;
927 }
928}
929
JP Abgrall7bdfa522013-11-15 13:42:56 -0800930static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
Ken Sumralle8744072011-01-18 22:01:55 -0800931 unsigned char *encrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700932 unsigned char *decrypted_master_key,
933 kdf_func kdf, void *kdf_params)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800934{
935 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800936 EVP_CIPHER_CTX d_ctx;
937 int decrypted_len, final_len;
938
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800939 /* Turn the password into a key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700940 kdf(passwd, salt, ikey, kdf_params);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800941
942 /* Initialize the decryption engine */
943 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
944 return -1;
945 }
946 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
947 /* Decrypt the master key */
948 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
949 encrypted_master_key, KEY_LEN_BYTES)) {
950 return -1;
951 }
952 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
953 return -1;
954 }
955
956 if (decrypted_len + final_len != KEY_LEN_BYTES) {
957 return -1;
958 } else {
959 return 0;
960 }
961}
962
Kenny Rootc4c70f12013-06-14 12:11:38 -0700963static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800964{
Kenny Rootc4c70f12013-06-14 12:11:38 -0700965 if (ftr->kdf_type == KDF_SCRYPT) {
966 *kdf = scrypt;
967 *kdf_params = ftr;
968 } else {
969 *kdf = pbkdf2;
970 *kdf_params = NULL;
971 }
972}
973
JP Abgrall7bdfa522013-11-15 13:42:56 -0800974static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700975 struct crypt_mnt_ftr *crypt_ftr)
976{
977 kdf_func kdf;
978 void *kdf_params;
979 int ret;
980
981 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
JP Abgrall7bdfa522013-11-15 13:42:56 -0800982 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, decrypted_master_key, kdf,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700983 kdf_params);
984 if (ret != 0) {
985 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -0700986 }
987
988 return ret;
989}
990
991static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
992 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800993 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -0800994 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800995 EVP_CIPHER_CTX e_ctx;
996 int encrypted_len, final_len;
997
998 /* Get some random bits for a key */
999 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001000 read(fd, key_buf, sizeof(key_buf));
1001 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001002 close(fd);
1003
1004 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001005 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001006}
1007
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001008static int wait_and_unmount(char *mountpoint)
1009{
1010 int i, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001011#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001012
1013 /* Now umount the tmpfs filesystem */
1014 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
1015 if (umount(mountpoint)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001016 if (errno == EINVAL) {
1017 /* EINVAL is returned if the directory is not a mountpoint,
1018 * i.e. there is no filesystem mounted there. So just get out.
1019 */
1020 break;
1021 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001022 sleep(1);
1023 i++;
1024 } else {
1025 break;
1026 }
1027 }
1028
1029 if (i < WAIT_UNMOUNT_COUNT) {
1030 SLOGD("unmounting %s succeeded\n", mountpoint);
1031 rc = 0;
1032 } else {
1033 SLOGE("unmounting %s failed\n", mountpoint);
1034 rc = -1;
1035 }
1036
1037 return rc;
1038}
1039
Ken Sumrallc5872692013-05-14 15:26:31 -07001040#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001041static int prep_data_fs(void)
1042{
1043 int i;
1044
1045 /* Do the prep of the /data filesystem */
1046 property_set("vold.post_fs_data_done", "0");
1047 property_set("vold.decrypt", "trigger_post_fs_data");
1048 SLOGD("Just triggered post_fs_data\n");
1049
Ken Sumrallc5872692013-05-14 15:26:31 -07001050 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001051 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001052 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001053
1054 property_get("vold.post_fs_data_done", p, "0");
1055 if (*p == '1') {
1056 break;
1057 } else {
1058 usleep(250000);
1059 }
1060 }
1061 if (i == DATA_PREP_TIMEOUT) {
1062 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001063 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001064 return -1;
1065 } else {
1066 SLOGD("post_fs_data done\n");
1067 return 0;
1068 }
1069}
1070
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001071int cryptfs_restart(void)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001072{
1073 char fs_type[32];
1074 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001075 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001076 char fs_options[256];
1077 unsigned long mnt_flags;
1078 struct stat statbuf;
1079 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001080 static int restart_successful = 0;
1081
1082 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001083 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001084 SLOGE("Encrypted filesystem not validated, aborting");
1085 return -1;
1086 }
1087
1088 if (restart_successful) {
1089 SLOGE("System already restarted with encrypted disk, aborting");
1090 return -1;
1091 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001092
1093 /* Here is where we shut down the framework. The init scripts
1094 * start all services in one of three classes: core, main or late_start.
1095 * On boot, we start core and main. Now, we stop main, but not core,
1096 * as core includes vold and a few other really important things that
1097 * we need to keep running. Once main has stopped, we should be able
1098 * to umount the tmpfs /data, then mount the encrypted /data.
1099 * We then restart the class main, and also the class late_start.
1100 * At the moment, I've only put a few things in late_start that I know
1101 * are not needed to bring up the framework, and that also cause problems
1102 * with unmounting the tmpfs /data, but I hope to add add more services
1103 * to the late_start class as we optimize this to decrease the delay
1104 * till the user is asked for the password to the filesystem.
1105 */
1106
1107 /* The init files are setup to stop the class main when vold.decrypt is
1108 * set to trigger_reset_main.
1109 */
1110 property_set("vold.decrypt", "trigger_reset_main");
1111 SLOGD("Just asked init to shut down class main\n");
1112
Ken Sumrall92736ef2012-10-17 20:57:14 -07001113 /* Ugh, shutting down the framework is not synchronous, so until it
1114 * can be fixed, this horrible hack will wait a moment for it all to
1115 * shut down before proceeding. Without it, some devices cannot
1116 * restart the graphics services.
1117 */
1118 sleep(2);
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001119
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001120 /* Now that the framework is shutdown, we should be able to umount()
1121 * the tmpfs filesystem, and mount the real one.
1122 */
1123
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001124 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1125 if (strlen(crypto_blkdev) == 0) {
1126 SLOGE("fs_crypto_blkdev not set\n");
1127 return -1;
1128 }
1129
Ken Sumralle5032c42012-04-01 23:58:44 -07001130 if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
1131 /* If that succeeded, then mount the decrypted filesystem */
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001132 fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001133
Ken Sumralle5032c42012-04-01 23:58:44 -07001134 property_set("vold.decrypt", "trigger_load_persist_props");
1135 /* Create necessary paths on /data */
1136 if (prep_data_fs()) {
1137 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001138 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001139
1140 /* startup service classes main and late_start */
1141 property_set("vold.decrypt", "trigger_restart_framework");
1142 SLOGD("Just triggered restart_framework\n");
1143
1144 /* Give it a few moments to get started */
1145 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001146 }
1147
Ken Sumrall0cc16632011-01-18 20:32:26 -08001148 if (rc == 0) {
1149 restart_successful = 1;
1150 }
1151
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001152 return rc;
1153}
1154
Mark Salyzyn5eecc442014-02-12 14:16:14 -08001155static int do_crypto_complete(char *mount_point UNUSED)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001156{
1157 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001158 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001159 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001160
1161 property_get("ro.crypto.state", encrypted_state, "");
1162 if (strcmp(encrypted_state, "encrypted") ) {
1163 SLOGE("not running with encryption, aborting");
1164 return 1;
1165 }
1166
Ken Sumrall160b4d62013-04-22 12:15:39 -07001167 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001168 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001169
Ken Sumralle1a45852011-12-14 21:24:27 -08001170 /*
1171 * Only report this error if key_loc is a file and it exists.
1172 * If the device was never encrypted, and /data is not mountable for
1173 * some reason, returning 1 should prevent the UI from presenting the
1174 * a "enter password" screen, or worse, a "press button to wipe the
1175 * device" screen.
1176 */
1177 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1178 SLOGE("master key file does not exist, aborting");
1179 return 1;
1180 } else {
1181 SLOGE("Error getting crypt footer and key\n");
1182 return -1;
1183 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001184 }
1185
1186 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1187 SLOGE("Encryption process didn't finish successfully\n");
1188 return -2; /* -2 is the clue to the UI that there is no usable data on the disk,
1189 * and give the user an option to wipe the disk */
1190 }
1191
1192 /* We passed the test! We shall diminish, and return to the west */
1193 return 0;
1194}
1195
Ken Sumrall29d8da82011-05-18 17:20:07 -07001196static int test_mount_encrypted_fs(char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001197{
1198 struct crypt_mnt_ftr crypt_ftr;
1199 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001200 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001201 char crypto_blkdev[MAXPATHLEN];
1202 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001203 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001204 unsigned int orig_failed_decrypt_count;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001205 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001206 int rc;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001207 kdf_func kdf;
1208 void *kdf_params;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001209
Ken Sumrall0cc16632011-01-18 20:32:26 -08001210 property_get("ro.crypto.state", encrypted_state, "");
Jason parks70a4b3f2011-01-28 10:10:47 -06001211 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001212 SLOGE("encrypted fs already validated or not running with encryption, aborting");
1213 return -1;
1214 }
1215
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001216 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001217
Ken Sumrall160b4d62013-04-22 12:15:39 -07001218 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001219 SLOGE("Error getting crypt footer and key\n");
1220 return -1;
1221 }
Ken Sumralld33d4172011-02-01 00:49:13 -08001222
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001223 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr.fs_size);
1224 orig_failed_decrypt_count = crypt_ftr.failed_decrypt_count;
1225
1226 if (! (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001227 if (decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr)) {
1228 SLOGE("Failed to decrypt master key\n");
1229 return -1;
1230 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001231 }
1232
1233 if (create_crypto_blk_dev(&crypt_ftr, decrypted_master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -07001234 real_blkdev, crypto_blkdev, label)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001235 SLOGE("Error creating decrypted block device\n");
1236 return -1;
1237 }
1238
Alex Klyubin707795a2013-05-10 15:17:07 -07001239 /* If init detects an encrypted filesystem, it writes a file for each such
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001240 * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
1241 * files and passes that data to me */
1242 /* Create a tmp mount point to try mounting the decryptd fs
1243 * Since we're here, the mount_point should be a tmpfs filesystem, so make
1244 * a directory in it to test mount the decrypted filesystem.
1245 */
1246 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1247 mkdir(tmp_mount_point, 0755);
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001248 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001249 SLOGE("Error temp mounting decrypted block device\n");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001250 delete_crypto_blk_dev(label);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001251 crypt_ftr.failed_decrypt_count++;
1252 } else {
1253 /* Success, so just umount and we'll mount it properly when we restart
1254 * the framework.
1255 */
1256 umount(tmp_mount_point);
1257 crypt_ftr.failed_decrypt_count = 0;
1258 }
1259
1260 if (orig_failed_decrypt_count != crypt_ftr.failed_decrypt_count) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001261 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001262 }
1263
1264 if (crypt_ftr.failed_decrypt_count) {
1265 /* We failed to mount the device, so return an error */
1266 rc = crypt_ftr.failed_decrypt_count;
1267
1268 } else {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001269 /* Woot! Success! Save the name of the crypto block device
1270 * so we can mount it when restarting the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001271 */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001272 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001273
1274 /* Also save a the master key so we can reencrypted the key
1275 * the key when we want to change the password on it.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001276 */
Jason parks70a4b3f2011-01-28 10:10:47 -06001277 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001278 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001279 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001280 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001281 rc = 0;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001282 /*
1283 * Upgrade if we're not using the latest KDF.
1284 */
1285 if (crypt_ftr.kdf_type != KDF_SCRYPT) {
1286 crypt_ftr.kdf_type = KDF_SCRYPT;
1287 rc = encrypt_master_key(passwd, crypt_ftr.salt, saved_master_key, crypt_ftr.master_key,
1288 &crypt_ftr);
1289 if (!rc) {
1290 rc = put_crypt_ftr_and_key(&crypt_ftr);
1291 }
1292 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1293 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001294 }
1295
1296 return rc;
1297}
1298
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001299/* Called by vold when it wants to undo the crypto mapping of a volume it
1300 * manages. This is usually in response to a factory reset, when we want
1301 * to undo the crypto mapping so the volume is formatted in the clear.
1302 */
1303int cryptfs_revert_volume(const char *label)
1304{
1305 return delete_crypto_blk_dev((char *)label);
1306}
1307
Ken Sumrall29d8da82011-05-18 17:20:07 -07001308/*
1309 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1310 * Setup a dm-crypt mapping, use the saved master key from
1311 * setting up the /data mapping, and return the new device path.
1312 */
1313int cryptfs_setup_volume(const char *label, int major, int minor,
1314 char *crypto_sys_path, unsigned int max_path,
1315 int *new_major, int *new_minor)
1316{
1317 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1318 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001319 struct stat statbuf;
1320 int nr_sec, fd;
1321
1322 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1323
Ken Sumrall160b4d62013-04-22 12:15:39 -07001324 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001325
1326 /* Update the fs_size field to be the size of the volume */
1327 fd = open(real_blkdev, O_RDONLY);
1328 nr_sec = get_blkdev_size(fd);
1329 close(fd);
1330 if (nr_sec == 0) {
1331 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1332 return -1;
1333 }
1334
1335 sd_crypt_ftr.fs_size = nr_sec;
1336 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1337 crypto_blkdev, label);
1338
1339 stat(crypto_blkdev, &statbuf);
1340 *new_major = MAJOR(statbuf.st_rdev);
1341 *new_minor = MINOR(statbuf.st_rdev);
1342
1343 /* Create path to sys entry for this block device */
1344 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1345
1346 return 0;
1347}
1348
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001349int cryptfs_crypto_complete(void)
1350{
1351 return do_crypto_complete("/data");
1352}
1353
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001354int cryptfs_check_passwd(char *passwd)
1355{
1356 int rc = -1;
1357
Ken Sumrall29d8da82011-05-18 17:20:07 -07001358 rc = test_mount_encrypted_fs(passwd, DATA_MNT_POINT, "userdata");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001359
1360 return rc;
1361}
1362
Ken Sumrall3ad90722011-10-04 20:38:29 -07001363int cryptfs_verify_passwd(char *passwd)
1364{
1365 struct crypt_mnt_ftr crypt_ftr;
1366 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001367 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001368 char encrypted_state[PROPERTY_VALUE_MAX];
1369 int rc;
1370
1371 property_get("ro.crypto.state", encrypted_state, "");
1372 if (strcmp(encrypted_state, "encrypted") ) {
1373 SLOGE("device not encrypted, aborting");
1374 return -2;
1375 }
1376
1377 if (!master_key_saved) {
1378 SLOGE("encrypted fs not yet mounted, aborting");
1379 return -1;
1380 }
1381
1382 if (!saved_mount_point) {
1383 SLOGE("encrypted fs failed to save mount point, aborting");
1384 return -1;
1385 }
1386
Ken Sumrall160b4d62013-04-22 12:15:39 -07001387 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001388 SLOGE("Error getting crypt footer and key\n");
1389 return -1;
1390 }
1391
1392 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1393 /* If the device has no password, then just say the password is valid */
1394 rc = 0;
1395 } else {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001396 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001397 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1398 /* They match, the password is correct */
1399 rc = 0;
1400 } else {
1401 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1402 sleep(1);
1403 rc = 1;
1404 }
1405 }
1406
1407 return rc;
1408}
1409
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001410/* Initialize a crypt_mnt_ftr structure. The keysize is
1411 * defaulted to 16 bytes, and the filesystem size to 0.
1412 * Presumably, at a minimum, the caller will update the
1413 * filesystem size and crypto_type_name after calling this function.
1414 */
1415static void cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
1416{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001417 off64_t off;
1418
1419 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001420 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001421 ftr->major_version = CURRENT_MAJOR_VERSION;
1422 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001423 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001424 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001425
Kenny Rootc4c70f12013-06-14 12:11:38 -07001426 ftr->kdf_type = KDF_SCRYPT;
1427 get_device_scrypt_params(ftr);
1428
Ken Sumrall160b4d62013-04-22 12:15:39 -07001429 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1430 if (get_crypt_ftr_info(NULL, &off) == 0) {
1431 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1432 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1433 ftr->persist_data_size;
1434 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001435}
1436
Ken Sumrall29d8da82011-05-18 17:20:07 -07001437static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001438{
Ken Sumralle550f782013-08-20 13:48:23 -07001439 const char *args[10];
1440 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1441 int num_args;
1442 int status;
1443 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001444 int rc = -1;
1445
Ken Sumrall29d8da82011-05-18 17:20:07 -07001446 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001447 args[0] = "/system/bin/make_ext4fs";
1448 args[1] = "-a";
1449 args[2] = "/data";
1450 args[3] = "-l";
1451 snprintf(size_str, sizeof(size_str), "%lld", size * 512);
1452 args[4] = size_str;
1453 args[5] = crypto_blkdev;
1454 num_args = 6;
1455 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1456 args[0], args[1], args[2], args[3], args[4], args[5]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001457 } else if (type== FAT_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001458 args[0] = "/system/bin/newfs_msdos";
1459 args[1] = "-F";
1460 args[2] = "32";
1461 args[3] = "-O";
1462 args[4] = "android";
1463 args[5] = "-c";
1464 args[6] = "8";
1465 args[7] = "-s";
1466 snprintf(size_str, sizeof(size_str), "%lld", size);
1467 args[8] = size_str;
1468 args[9] = crypto_blkdev;
1469 num_args = 10;
1470 SLOGI("Making empty filesystem with command %s %s %s %s %s %s %s %s %s %s\n",
1471 args[0], args[1], args[2], args[3], args[4], args[5],
1472 args[6], args[7], args[8], args[9]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001473 } else {
1474 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1475 return -1;
1476 }
1477
Ken Sumralle550f782013-08-20 13:48:23 -07001478 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1479
1480 if (tmp != 0) {
1481 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001482 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07001483 if (WIFEXITED(status)) {
1484 if (WEXITSTATUS(status)) {
1485 SLOGE("Error creating filesystem on %s, exit status %d ",
1486 crypto_blkdev, WEXITSTATUS(status));
1487 } else {
1488 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
1489 rc = 0;
1490 }
1491 } else {
1492 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
1493 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001494 }
1495
1496 return rc;
1497}
1498
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001499#define CRYPT_INPLACE_BUFSIZE 4096
1500#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / 512)
Ken Sumrall29d8da82011-05-18 17:20:07 -07001501static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev, off64_t size,
1502 off64_t *size_already_done, off64_t tot_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001503{
1504 int realfd, cryptofd;
1505 char *buf[CRYPT_INPLACE_BUFSIZE];
1506 int rc = -1;
1507 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001508 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001509 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001510
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001511 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
1512 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
1513 return -1;
1514 }
1515
1516 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
1517 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1518 close(realfd);
1519 return -1;
1520 }
1521
1522 /* This is pretty much a simple loop of reading 4K, and writing 4K.
1523 * The size passed in is the number of 512 byte sectors in the filesystem.
1524 * So compute the number of whole 4K blocks we should read/write,
1525 * and the remainder.
1526 */
1527 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
1528 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001529 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
1530 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001531
1532 SLOGE("Encrypting filesystem in place...");
1533
Ken Sumrall29d8da82011-05-18 17:20:07 -07001534 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001535 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001536 /* process the majority of the filesystem in blocks */
1537 for (i=0; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001538 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001539 if (new_pct > cur_pct) {
1540 char buf[8];
1541
1542 cur_pct = new_pct;
1543 snprintf(buf, sizeof(buf), "%lld", cur_pct);
1544 property_set("vold.encrypt_progress", buf);
1545 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001546 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1547 SLOGE("Error reading real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1548 goto errout;
1549 }
1550 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1551 SLOGE("Error writing crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1552 goto errout;
1553 }
1554 }
1555
1556 /* Do any remaining sectors */
1557 for (i=0; i<remainder; i++) {
1558 if (unix_read(realfd, buf, 512) <= 0) {
1559 SLOGE("Error reading rival sectors from real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1560 goto errout;
1561 }
1562 if (unix_write(cryptofd, buf, 512) <= 0) {
1563 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1564 goto errout;
1565 }
1566 }
1567
Ken Sumrall29d8da82011-05-18 17:20:07 -07001568 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001569 rc = 0;
1570
1571errout:
1572 close(realfd);
1573 close(cryptofd);
1574
1575 return rc;
1576}
1577
1578#define CRYPTO_ENABLE_WIPE 1
1579#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001580
1581#define FRAMEWORK_BOOT_WAIT 60
1582
Ken Sumrall29d8da82011-05-18 17:20:07 -07001583static inline int should_encrypt(struct volume_info *volume)
1584{
1585 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
1586 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
1587}
1588
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001589int cryptfs_enable(char *howarg, char *passwd)
1590{
1591 int how = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001592 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN], sd_crypto_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07001593 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001594 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07001595 int rc=-1, fd, i, ret;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001596 struct crypt_mnt_ftr crypt_ftr, sd_crypt_ftr;;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001597 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001598 char tmpfs_options[PROPERTY_VALUE_MAX];
1599 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001600 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07001601 char key_loc[PROPERTY_VALUE_MAX];
1602 char fuse_sdcard[PROPERTY_VALUE_MAX];
1603 char *sd_mnt_point;
1604 char sd_blk_dev[256] = { 0 };
1605 int num_vols;
1606 struct volume_info *vol_list = 0;
1607 off64_t cur_encryption_done=0, tot_encryption_size=0;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001608
1609 property_get("ro.crypto.state", encrypted_state, "");
1610 if (strcmp(encrypted_state, "unencrypted")) {
1611 SLOGE("Device is already running encrypted, aborting");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001612 goto error_unencrypted;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001613 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001614
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001615 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001616
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001617 if (!strcmp(howarg, "wipe")) {
1618 how = CRYPTO_ENABLE_WIPE;
1619 } else if (! strcmp(howarg, "inplace")) {
1620 how = CRYPTO_ENABLE_INPLACE;
1621 } else {
1622 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08001623 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001624 }
1625
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001626 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001627
Ken Sumrall3ed82362011-01-28 23:31:16 -08001628 /* Get the size of the real block device */
1629 fd = open(real_blkdev, O_RDONLY);
1630 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
1631 SLOGE("Cannot get size of block device %s\n", real_blkdev);
1632 goto error_unencrypted;
1633 }
1634 close(fd);
1635
1636 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001637 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001638 unsigned int fs_size_sec, max_fs_size_sec;
1639
1640 fs_size_sec = get_fs_size(real_blkdev);
1641 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1642
1643 if (fs_size_sec > max_fs_size_sec) {
1644 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
1645 goto error_unencrypted;
1646 }
1647 }
1648
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001649 /* Get a wakelock as this may take a while, and we don't want the
1650 * device to sleep on us. We'll grab a partial wakelock, and if the UI
1651 * wants to keep the screen on, it can grab a full wakelock.
1652 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001653 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001654 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
1655
Jeff Sharkey7382f812012-08-23 14:08:59 -07001656 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07001657 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07001658 if (!sd_mnt_point) {
1659 sd_mnt_point = getenv("EXTERNAL_STORAGE");
1660 }
1661 if (!sd_mnt_point) {
1662 sd_mnt_point = "/mnt/sdcard";
1663 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07001664
1665 num_vols=vold_getNumDirectVolumes();
1666 vol_list = malloc(sizeof(struct volume_info) * num_vols);
1667 vold_getDirectVolumeList(vol_list);
1668
1669 for (i=0; i<num_vols; i++) {
1670 if (should_encrypt(&vol_list[i])) {
1671 fd = open(vol_list[i].blk_dev, O_RDONLY);
1672 if ( (vol_list[i].size = get_blkdev_size(fd)) == 0) {
1673 SLOGE("Cannot get size of block device %s\n", vol_list[i].blk_dev);
1674 goto error_unencrypted;
1675 }
1676 close(fd);
1677
Ken Sumrall3b170052011-07-11 15:38:57 -07001678 ret=vold_disableVol(vol_list[i].label);
Ken Sumrall319b1042011-06-14 14:01:55 -07001679 if ((ret < 0) && (ret != UNMOUNT_NOT_MOUNTED_ERR)) {
1680 /* -2 is returned when the device exists but is not currently mounted.
1681 * ignore the error and continue. */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001682 SLOGE("Failed to unmount volume %s\n", vol_list[i].label);
1683 goto error_unencrypted;
1684 }
1685 }
1686 }
1687
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001688 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001689 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001690 */
1691 property_set("vold.decrypt", "trigger_shutdown_framework");
1692 SLOGD("Just asked init to shut down class main\n");
1693
Ken Sumrall425524d2012-06-14 20:55:28 -07001694 if (vold_unmountAllAsecs()) {
1695 /* Just report the error. If any are left mounted,
1696 * umounting /data below will fail and handle the error.
1697 */
1698 SLOGE("Error unmounting internal asecs");
1699 }
1700
Ken Sumrall29d8da82011-05-18 17:20:07 -07001701 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
1702 if (!strcmp(fuse_sdcard, "true")) {
1703 /* This is a device using the fuse layer to emulate the sdcard semantics
1704 * on top of the userdata partition. vold does not manage it, it is managed
1705 * by the sdcard service. The sdcard service was killed by the property trigger
1706 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
1707 * unlike the case for vold managed devices above.
1708 */
1709 if (wait_and_unmount(sd_mnt_point)) {
1710 goto error_shutting_down;
1711 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001712 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001713
1714 /* Now unmount the /data partition. */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001715 if (wait_and_unmount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001716 goto error_shutting_down;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001717 }
1718
1719 /* Do extra work for a better UX when doing the long inplace encryption */
1720 if (how == CRYPTO_ENABLE_INPLACE) {
1721 /* Now that /data is unmounted, we need to mount a tmpfs
1722 * /data, set a property saying we're doing inplace encryption,
1723 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001724 */
Ken Sumralle5032c42012-04-01 23:58:44 -07001725 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001726 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001727 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001728 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08001729 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001730
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001731 /* restart the framework. */
1732 /* Create necessary paths on /data */
1733 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001734 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001735 }
1736
Ken Sumrall92736ef2012-10-17 20:57:14 -07001737 /* Ugh, shutting down the framework is not synchronous, so until it
1738 * can be fixed, this horrible hack will wait a moment for it all to
1739 * shut down before proceeding. Without it, some devices cannot
1740 * restart the graphics services.
1741 */
1742 sleep(2);
1743
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001744 /* startup service classes main and late_start */
1745 property_set("vold.decrypt", "trigger_restart_min_framework");
1746 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001747
Ken Sumrall7df84122011-01-18 14:04:08 -08001748 /* OK, the framework is restarted and will soon be showing a
1749 * progress bar. Time to setup an encrypted mapping, and
1750 * either write a new filesystem, or encrypt in place updating
1751 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001752 */
1753 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001754
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001755 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001756 /* Initialize a crypt_mnt_ftr for the partition */
1757 cryptfs_init_crypt_mnt_ftr(&crypt_ftr);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001758
Ken Sumrall29d8da82011-05-18 17:20:07 -07001759 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
1760 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1761 } else {
1762 crypt_ftr.fs_size = nr_sec;
1763 }
Ken Sumralld33d4172011-02-01 00:49:13 -08001764 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001765 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
1766
1767 /* Make an encrypted master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001768 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001769 SLOGE("Cannot create encrypted master key\n");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001770 goto error_unencrypted;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001771 }
1772
1773 /* Write the key to the end of the partition */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001774 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001775
Ken Sumrall160b4d62013-04-22 12:15:39 -07001776 /* If any persistent data has been remembered, save it.
1777 * If none, create a valid empty table and save that.
1778 */
1779 if (!persist_data) {
1780 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
1781 if (pdata) {
1782 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
1783 persist_data = pdata;
1784 }
1785 }
1786 if (persist_data) {
1787 save_persistent_data();
1788 }
1789
JP Abgrall7bdfa522013-11-15 13:42:56 -08001790 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001791 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
1792 "userdata");
1793
Ken Sumrall128626f2011-06-28 18:45:14 -07001794 /* The size of the userdata partition, and add in the vold volumes below */
1795 tot_encryption_size = crypt_ftr.fs_size;
1796
Ken Sumrall29d8da82011-05-18 17:20:07 -07001797 /* setup crypto mapping for all encryptable volumes handled by vold */
1798 for (i=0; i<num_vols; i++) {
1799 if (should_encrypt(&vol_list[i])) {
1800 vol_list[i].crypt_ftr = crypt_ftr; /* gotta love struct assign */
1801 vol_list[i].crypt_ftr.fs_size = vol_list[i].size;
1802 create_crypto_blk_dev(&vol_list[i].crypt_ftr, decrypted_master_key,
1803 vol_list[i].blk_dev, vol_list[i].crypto_blkdev,
1804 vol_list[i].label);
Ken Sumrall128626f2011-06-28 18:45:14 -07001805 tot_encryption_size += vol_list[i].size;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001806 }
1807 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001808
1809 if (how == CRYPTO_ENABLE_WIPE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001810 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr.fs_size, EXT4_FS);
1811 /* Encrypt all encryptable volumes handled by vold */
1812 if (!rc) {
1813 for (i=0; i<num_vols; i++) {
1814 if (should_encrypt(&vol_list[i])) {
1815 rc = cryptfs_enable_wipe(vol_list[i].crypto_blkdev,
1816 vol_list[i].crypt_ftr.fs_size, FAT_FS);
1817 }
1818 }
1819 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001820 } else if (how == CRYPTO_ENABLE_INPLACE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001821 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr.fs_size,
1822 &cur_encryption_done, tot_encryption_size);
1823 /* Encrypt all encryptable volumes handled by vold */
1824 if (!rc) {
1825 for (i=0; i<num_vols; i++) {
1826 if (should_encrypt(&vol_list[i])) {
1827 rc = cryptfs_enable_inplace(vol_list[i].crypto_blkdev,
1828 vol_list[i].blk_dev,
1829 vol_list[i].crypt_ftr.fs_size,
1830 &cur_encryption_done, tot_encryption_size);
1831 }
1832 }
1833 }
1834 if (!rc) {
1835 /* The inplace routine never actually sets the progress to 100%
1836 * due to the round down nature of integer division, so set it here */
1837 property_set("vold.encrypt_progress", "100");
1838 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001839 } else {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001840 /* Shouldn't happen */
1841 SLOGE("cryptfs_enable: internal error, unknown option\n");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001842 goto error_unencrypted;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001843 }
1844
1845 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001846 delete_crypto_blk_dev("userdata");
1847 for (i=0; i<num_vols; i++) {
1848 if (should_encrypt(&vol_list[i])) {
1849 delete_crypto_blk_dev(vol_list[i].label);
1850 }
1851 }
1852
1853 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001854
1855 if (! rc) {
1856 /* Success */
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001857
Ken Sumralld33d4172011-02-01 00:49:13 -08001858 /* Clear the encryption in progres flag in the footer */
1859 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001860 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08001861
Ken Sumrall29d8da82011-05-18 17:20:07 -07001862 sleep(2); /* Give the UI a chance to show 100% progress */
Ken Sumralladfba362013-06-04 16:37:52 -07001863 cryptfs_reboot(0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001864 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001865 char value[PROPERTY_VALUE_MAX];
1866
Ken Sumrall319369a2012-06-27 16:30:18 -07001867 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001868 if (!strcmp(value, "1")) {
1869 /* wipe data if encryption failed */
1870 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
1871 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07001872 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001873 if (fd >= 0) {
1874 write(fd, "--wipe_data", strlen("--wipe_data") + 1);
1875 close(fd);
1876 } else {
1877 SLOGE("could not open /cache/recovery/command\n");
1878 }
Ken Sumralladfba362013-06-04 16:37:52 -07001879 cryptfs_reboot(1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001880 } else {
1881 /* set property to trigger dialog */
1882 property_set("vold.encrypt_progress", "error_partially_encrypted");
1883 release_wake_lock(lockid);
1884 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001885 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001886 }
1887
Ken Sumrall3ed82362011-01-28 23:31:16 -08001888 /* hrm, the encrypt step claims success, but the reboot failed.
1889 * This should not happen.
1890 * Set the property and return. Hope the framework can deal with it.
1891 */
1892 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001893 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001894 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08001895
1896error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07001897 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001898 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001899 if (lockid[0]) {
1900 release_wake_lock(lockid);
1901 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001902 return -1;
1903
1904error_shutting_down:
1905 /* we failed, and have not encrypted anthing, so the users's data is still intact,
1906 * but the framework is stopped and not restarted to show the error, so it's up to
1907 * vold to restart the system.
1908 */
1909 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Ken Sumralladfba362013-06-04 16:37:52 -07001910 cryptfs_reboot(0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001911
1912 /* shouldn't get here */
1913 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001914 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001915 if (lockid[0]) {
1916 release_wake_lock(lockid);
1917 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001918 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001919}
1920
Jason parks70a4b3f2011-01-28 10:10:47 -06001921int cryptfs_changepw(char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001922{
1923 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001924 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001925
1926 /* This is only allowed after we've successfully decrypted the master key */
Jason parks70a4b3f2011-01-28 10:10:47 -06001927 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001928 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001929 return -1;
1930 }
1931
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001932 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001933 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall57b63e62011-01-17 18:29:19 -08001934 SLOGE("Error getting crypt footer and key");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001935 return -1;
1936 }
1937
Kenny Rootc4c70f12013-06-14 12:11:38 -07001938 encrypt_master_key(newpw, crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001939
Jason parks70a4b3f2011-01-28 10:10:47 -06001940 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001941 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001942
1943 return 0;
1944}
Ken Sumrall160b4d62013-04-22 12:15:39 -07001945
1946static int persist_get_key(char *fieldname, char *value)
1947{
1948 unsigned int i;
1949
1950 if (persist_data == NULL) {
1951 return -1;
1952 }
1953 for (i = 0; i < persist_data->persist_valid_entries; i++) {
1954 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
1955 /* We found it! */
1956 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
1957 return 0;
1958 }
1959 }
1960
1961 return -1;
1962}
1963
1964static int persist_set_key(char *fieldname, char *value, int encrypted)
1965{
1966 unsigned int i;
1967 unsigned int num;
1968 struct crypt_mnt_ftr crypt_ftr;
1969 unsigned int max_persistent_entries;
1970 unsigned int dsize;
1971
1972 if (persist_data == NULL) {
1973 return -1;
1974 }
1975
1976 /* If encrypted, use the values from the crypt_ftr, otherwise
1977 * use the values for the current spec.
1978 */
1979 if (encrypted) {
1980 if(get_crypt_ftr_and_key(&crypt_ftr)) {
1981 return -1;
1982 }
1983 dsize = crypt_ftr.persist_data_size;
1984 } else {
1985 dsize = CRYPT_PERSIST_DATA_SIZE;
1986 }
1987 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
1988 sizeof(struct crypt_persist_entry);
1989
1990 num = persist_data->persist_valid_entries;
1991
1992 for (i = 0; i < num; i++) {
1993 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
1994 /* We found an existing entry, update it! */
1995 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
1996 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
1997 return 0;
1998 }
1999 }
2000
2001 /* We didn't find it, add it to the end, if there is room */
2002 if (persist_data->persist_valid_entries < max_persistent_entries) {
2003 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2004 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2005 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2006 persist_data->persist_valid_entries++;
2007 return 0;
2008 }
2009
2010 return -1;
2011}
2012
2013/* Return the value of the specified field. */
2014int cryptfs_getfield(char *fieldname, char *value, int len)
2015{
2016 char temp_value[PROPERTY_VALUE_MAX];
2017 char real_blkdev[MAXPATHLEN];
2018 /* 0 is success, 1 is not encrypted,
2019 * -1 is value not set, -2 is any other error
2020 */
2021 int rc = -2;
2022
2023 if (persist_data == NULL) {
2024 load_persistent_data();
2025 if (persist_data == NULL) {
2026 SLOGE("Getfield error, cannot load persistent data");
2027 goto out;
2028 }
2029 }
2030
2031 if (!persist_get_key(fieldname, temp_value)) {
2032 /* We found it, copy it to the caller's buffer and return */
2033 strlcpy(value, temp_value, len);
2034 rc = 0;
2035 } else {
2036 /* Sadness, it's not there. Return the error */
2037 rc = -1;
2038 }
2039
2040out:
2041 return rc;
2042}
2043
2044/* Set the value of the specified field. */
2045int cryptfs_setfield(char *fieldname, char *value)
2046{
2047 struct crypt_persist_data stored_pdata;
2048 struct crypt_persist_data *pdata_p;
2049 struct crypt_mnt_ftr crypt_ftr;
2050 char encrypted_state[PROPERTY_VALUE_MAX];
2051 /* 0 is success, -1 is an error */
2052 int rc = -1;
2053 int encrypted = 0;
2054
2055 if (persist_data == NULL) {
2056 load_persistent_data();
2057 if (persist_data == NULL) {
2058 SLOGE("Setfield error, cannot load persistent data");
2059 goto out;
2060 }
2061 }
2062
2063 property_get("ro.crypto.state", encrypted_state, "");
2064 if (!strcmp(encrypted_state, "encrypted") ) {
2065 encrypted = 1;
2066 }
2067
2068 if (persist_set_key(fieldname, value, encrypted)) {
2069 goto out;
2070 }
2071
2072 /* If we are running encrypted, save the persistent data now */
2073 if (encrypted) {
2074 if (save_persistent_data()) {
2075 SLOGE("Setfield error, cannot save persistent data");
2076 goto out;
2077 }
2078 }
2079
2080 rc = 0;
2081
2082out:
2083 return rc;
2084}