blob: 3eab6ac8a5b82afded333ff707021e3796ea4076 [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>
Elliott Hughes73737162014-06-25 17:27:42 -070027#include <inttypes.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080028#include <unistd.h>
29#include <stdio.h>
30#include <sys/ioctl.h>
31#include <linux/dm-ioctl.h>
32#include <libgen.h>
33#include <stdlib.h>
34#include <sys/param.h>
35#include <string.h>
36#include <sys/mount.h>
37#include <openssl/evp.h>
Ken Sumrall8ddbe402011-01-17 15:26:29 -080038#include <openssl/sha.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080039#include <errno.h>
Ken Sumrall3ed82362011-01-28 23:31:16 -080040#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070041#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070042#include <fs_mgr.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080043#include "cryptfs.h"
44#define LOG_TAG "Cryptfs"
45#include "cutils/log.h"
46#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070047#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080048#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070049#include <logwrap/logwrap.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070050#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070051#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070052#include "crypto_scrypt.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080053
Mark Salyzyn5eecc442014-02-12 14:16:14 -080054#define UNUSED __attribute__((unused))
55
Ken Sumrall8f869aa2010-12-03 03:47:09 -080056#define DM_CRYPT_BUF_SIZE 4096
Ken Sumrall8ddbe402011-01-17 15:26:29 -080057#define DATA_MNT_POINT "/data"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080058
Jason parks70a4b3f2011-01-28 10:10:47 -060059#define HASH_COUNT 2000
60#define KEY_LEN_BYTES 16
61#define IV_LEN_BYTES 16
62
Ken Sumrall29d8da82011-05-18 17:20:07 -070063#define KEY_IN_FOOTER "footer"
64
65#define EXT4_FS 1
66#define FAT_FS 2
67
Ken Sumralle919efe2012-09-29 17:07:41 -070068#define TABLE_LOAD_RETRIES 10
69
Ken Sumrall8f869aa2010-12-03 03:47:09 -080070char *me = "cryptfs";
71
Jason parks70a4b3f2011-01-28 10:10:47 -060072static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070073static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060074static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -070075static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -080076
77extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -080078
Ken Sumralladfba362013-06-04 16:37:52 -070079static void cryptfs_reboot(int recovery)
80{
81 if (recovery) {
82 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
83 } else {
84 property_set(ANDROID_RB_PROPERTY, "reboot");
85 }
86 sleep(20);
87
88 /* Shouldn't get here, reboot should happen before sleep times out */
89 return;
90}
91
Ken Sumrall8f869aa2010-12-03 03:47:09 -080092static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
93{
94 memset(io, 0, dataSize);
95 io->data_size = dataSize;
96 io->data_start = sizeof(struct dm_ioctl);
97 io->version[0] = 4;
98 io->version[1] = 0;
99 io->version[2] = 0;
100 io->flags = flags;
101 if (name) {
102 strncpy(io->name, name, sizeof(io->name));
103 }
104}
105
Kenny Rootc4c70f12013-06-14 12:11:38 -0700106/**
107 * Gets the default device scrypt parameters for key derivation time tuning.
108 * The parameters should lead to about one second derivation time for the
109 * given device.
110 */
111static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
112 const int default_params[] = SCRYPT_DEFAULTS;
113 int params[] = SCRYPT_DEFAULTS;
114 char paramstr[PROPERTY_VALUE_MAX];
115 char *token;
116 char *saveptr;
117 int i;
118
119 property_get(SCRYPT_PROP, paramstr, "");
120 if (paramstr[0] != '\0') {
121 /*
122 * The token we're looking for should be three integers separated by
123 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
124 */
Kenny Root2947e342013-08-14 15:54:49 -0700125 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
126 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700127 i++, token = strtok_r(NULL, ":", &saveptr)) {
128 char *endptr;
129 params[i] = strtol(token, &endptr, 10);
130
131 /*
132 * Check that there was a valid number and it's 8-bit. If not,
133 * break out and the end check will take the default values.
134 */
135 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
136 break;
137 }
138 }
139
140 /*
141 * If there were not enough tokens or a token was malformed (not an
142 * integer), it will end up here and the default parameters can be
143 * taken.
144 */
145 if ((i != 3) || (token != NULL)) {
146 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
147 memcpy(params, default_params, sizeof(params));
148 }
149 }
150
151 ftr->N_factor = params[0];
152 ftr->r_factor = params[1];
153 ftr->p_factor = params[2];
154}
155
Ken Sumrall3ed82362011-01-28 23:31:16 -0800156static unsigned int get_fs_size(char *dev)
157{
158 int fd, block_size;
159 struct ext4_super_block sb;
160 off64_t len;
161
162 if ((fd = open(dev, O_RDONLY)) < 0) {
163 SLOGE("Cannot open device to get filesystem size ");
164 return 0;
165 }
166
167 if (lseek64(fd, 1024, SEEK_SET) < 0) {
168 SLOGE("Cannot seek to superblock");
169 return 0;
170 }
171
172 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
173 SLOGE("Cannot read superblock");
174 return 0;
175 }
176
177 close(fd);
178
179 block_size = 1024 << sb.s_log_block_size;
180 /* compute length in bytes */
181 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
182
183 /* return length in sectors */
184 return (unsigned int) (len / 512);
185}
186
Ken Sumrall160b4d62013-04-22 12:15:39 -0700187static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
188{
189 static int cached_data = 0;
190 static off64_t cached_off = 0;
191 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
192 int fd;
193 char key_loc[PROPERTY_VALUE_MAX];
194 char real_blkdev[PROPERTY_VALUE_MAX];
195 unsigned int nr_sec;
196 int rc = -1;
197
198 if (!cached_data) {
199 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
200
201 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
202 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
203 SLOGE("Cannot open real block device %s\n", real_blkdev);
204 return -1;
205 }
206
207 if ((nr_sec = get_blkdev_size(fd))) {
208 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
209 * encryption info footer and key, and plenty of bytes to spare for future
210 * growth.
211 */
212 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
213 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
214 cached_data = 1;
215 } else {
216 SLOGE("Cannot get size of block device %s\n", real_blkdev);
217 }
218 close(fd);
219 } else {
220 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
221 cached_off = 0;
222 cached_data = 1;
223 }
224 }
225
226 if (cached_data) {
227 if (metadata_fname) {
228 *metadata_fname = cached_metadata_fname;
229 }
230 if (off) {
231 *off = cached_off;
232 }
233 rc = 0;
234 }
235
236 return rc;
237}
238
Ken Sumralle8744072011-01-18 22:01:55 -0800239/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800240 * update the failed mount count but not change the key.
241 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700242static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800243{
244 int fd;
245 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700246 /* starting_off is set to the SEEK_SET offset
247 * where the crypto structure starts
248 */
249 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800250 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700251 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700252 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800253
Ken Sumrall160b4d62013-04-22 12:15:39 -0700254 if (get_crypt_ftr_info(&fname, &starting_off)) {
255 SLOGE("Unable to get crypt_ftr_info\n");
256 return -1;
257 }
258 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700259 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700260 return -1;
261 }
Ken Sumralle550f782013-08-20 13:48:23 -0700262 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
263 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700264 return -1;
265 }
266
267 /* Seek to the start of the crypt footer */
268 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
269 SLOGE("Cannot seek to real block device footer\n");
270 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800271 }
272
273 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
274 SLOGE("Cannot write real block device footer\n");
275 goto errout;
276 }
277
Ken Sumrall3be890f2011-09-14 16:53:46 -0700278 fstat(fd, &statbuf);
279 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700280 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700281 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800282 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800283 goto errout;
284 }
285 }
286
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800287 /* Success! */
288 rc = 0;
289
290errout:
291 close(fd);
292 return rc;
293
294}
295
Ken Sumrall160b4d62013-04-22 12:15:39 -0700296static inline int unix_read(int fd, void* buff, int len)
297{
298 return TEMP_FAILURE_RETRY(read(fd, buff, len));
299}
300
301static inline int unix_write(int fd, const void* buff, int len)
302{
303 return TEMP_FAILURE_RETRY(write(fd, buff, len));
304}
305
306static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
307{
308 memset(pdata, 0, len);
309 pdata->persist_magic = PERSIST_DATA_MAGIC;
310 pdata->persist_valid_entries = 0;
311}
312
313/* A routine to update the passed in crypt_ftr to the lastest version.
314 * fd is open read/write on the device that holds the crypto footer and persistent
315 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
316 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
317 */
318static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
319{
Kenny Root7434b312013-06-14 11:29:53 -0700320 int orig_major = crypt_ftr->major_version;
321 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700322
Kenny Root7434b312013-06-14 11:29:53 -0700323 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
324 struct crypt_persist_data *pdata;
325 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700326
Kenny Rootc4c70f12013-06-14 12:11:38 -0700327 SLOGW("upgrading crypto footer to 1.1");
328
Kenny Root7434b312013-06-14 11:29:53 -0700329 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
330 if (pdata == NULL) {
331 SLOGE("Cannot allocate persisent data\n");
332 return;
333 }
334 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
335
336 /* Need to initialize the persistent data area */
337 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
338 SLOGE("Cannot seek to persisent data offset\n");
339 return;
340 }
341 /* Write all zeros to the first copy, making it invalid */
342 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
343
344 /* Write a valid but empty structure to the second copy */
345 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
346 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
347
348 /* Update the footer */
349 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
350 crypt_ftr->persist_data_offset[0] = pdata_offset;
351 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
352 crypt_ftr->minor_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700353 }
354
Kenny Rootc4c70f12013-06-14 12:11:38 -0700355 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version)) {
356 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800357 /* But keep the old kdf_type.
358 * It will get updated later to KDF_SCRYPT after the password has been verified.
359 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700360 crypt_ftr->kdf_type = KDF_PBKDF2;
361 get_device_scrypt_params(crypt_ftr);
362 crypt_ftr->minor_version = 2;
363 }
364
Kenny Root7434b312013-06-14 11:29:53 -0700365 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
366 if (lseek64(fd, offset, SEEK_SET) == -1) {
367 SLOGE("Cannot seek to crypt footer\n");
368 return;
369 }
370 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700371 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700372}
373
374
375static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800376{
377 int fd;
378 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700379 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800380 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700381 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700382 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800383
Ken Sumrall160b4d62013-04-22 12:15:39 -0700384 if (get_crypt_ftr_info(&fname, &starting_off)) {
385 SLOGE("Unable to get crypt_ftr_info\n");
386 return -1;
387 }
388 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700389 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700390 return -1;
391 }
392 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700393 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700394 return -1;
395 }
396
397 /* Make sure it's 16 Kbytes in length */
398 fstat(fd, &statbuf);
399 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
400 SLOGE("footer file %s is not the expected size!\n", fname);
401 goto errout;
402 }
403
404 /* Seek to the start of the crypt footer */
405 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
406 SLOGE("Cannot seek to real block device footer\n");
407 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800408 }
409
410 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
411 SLOGE("Cannot read real block device footer\n");
412 goto errout;
413 }
414
415 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700416 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800417 goto errout;
418 }
419
Kenny Rootc96a5f82013-06-14 12:08:28 -0700420 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
421 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
422 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800423 goto errout;
424 }
425
Kenny Rootc96a5f82013-06-14 12:08:28 -0700426 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
427 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
428 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800429 }
430
Ken Sumrall160b4d62013-04-22 12:15:39 -0700431 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
432 * copy on disk before returning.
433 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700434 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700435 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800436 }
437
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800438 /* Success! */
439 rc = 0;
440
441errout:
442 close(fd);
443 return rc;
444}
445
Ken Sumrall160b4d62013-04-22 12:15:39 -0700446static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
447{
448 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
449 crypt_ftr->persist_data_offset[1]) {
450 SLOGE("Crypt_ftr persist data regions overlap");
451 return -1;
452 }
453
454 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
455 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
456 return -1;
457 }
458
459 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
460 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
461 CRYPT_FOOTER_OFFSET) {
462 SLOGE("Persistent data extends past crypto footer");
463 return -1;
464 }
465
466 return 0;
467}
468
469static int load_persistent_data(void)
470{
471 struct crypt_mnt_ftr crypt_ftr;
472 struct crypt_persist_data *pdata = NULL;
473 char encrypted_state[PROPERTY_VALUE_MAX];
474 char *fname;
475 int found = 0;
476 int fd;
477 int ret;
478 int i;
479
480 if (persist_data) {
481 /* Nothing to do, we've already loaded or initialized it */
482 return 0;
483 }
484
485
486 /* If not encrypted, just allocate an empty table and initialize it */
487 property_get("ro.crypto.state", encrypted_state, "");
488 if (strcmp(encrypted_state, "encrypted") ) {
489 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
490 if (pdata) {
491 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
492 persist_data = pdata;
493 return 0;
494 }
495 return -1;
496 }
497
498 if(get_crypt_ftr_and_key(&crypt_ftr)) {
499 return -1;
500 }
501
502 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
503 SLOGE("Crypt_ftr version doesn't support persistent data");
504 return -1;
505 }
506
507 if (get_crypt_ftr_info(&fname, NULL)) {
508 return -1;
509 }
510
511 ret = validate_persistent_data_storage(&crypt_ftr);
512 if (ret) {
513 return -1;
514 }
515
516 fd = open(fname, O_RDONLY);
517 if (fd < 0) {
518 SLOGE("Cannot open %s metadata file", fname);
519 return -1;
520 }
521
522 if (persist_data == NULL) {
523 pdata = malloc(crypt_ftr.persist_data_size);
524 if (pdata == NULL) {
525 SLOGE("Cannot allocate memory for persistent data");
526 goto err;
527 }
528 }
529
530 for (i = 0; i < 2; i++) {
531 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
532 SLOGE("Cannot seek to read persistent data on %s", fname);
533 goto err2;
534 }
535 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
536 SLOGE("Error reading persistent data on iteration %d", i);
537 goto err2;
538 }
539 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
540 found = 1;
541 break;
542 }
543 }
544
545 if (!found) {
546 SLOGI("Could not find valid persistent data, creating");
547 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
548 }
549
550 /* Success */
551 persist_data = pdata;
552 close(fd);
553 return 0;
554
555err2:
556 free(pdata);
557
558err:
559 close(fd);
560 return -1;
561}
562
563static int save_persistent_data(void)
564{
565 struct crypt_mnt_ftr crypt_ftr;
566 struct crypt_persist_data *pdata;
567 char *fname;
568 off64_t write_offset;
569 off64_t erase_offset;
570 int found = 0;
571 int fd;
572 int ret;
573
574 if (persist_data == NULL) {
575 SLOGE("No persistent data to save");
576 return -1;
577 }
578
579 if(get_crypt_ftr_and_key(&crypt_ftr)) {
580 return -1;
581 }
582
583 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
584 SLOGE("Crypt_ftr version doesn't support persistent data");
585 return -1;
586 }
587
588 ret = validate_persistent_data_storage(&crypt_ftr);
589 if (ret) {
590 return -1;
591 }
592
593 if (get_crypt_ftr_info(&fname, NULL)) {
594 return -1;
595 }
596
597 fd = open(fname, O_RDWR);
598 if (fd < 0) {
599 SLOGE("Cannot open %s metadata file", fname);
600 return -1;
601 }
602
603 pdata = malloc(crypt_ftr.persist_data_size);
604 if (pdata == NULL) {
605 SLOGE("Cannot allocate persistant data");
606 goto err;
607 }
608
609 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
610 SLOGE("Cannot seek to read persistent data on %s", fname);
611 goto err2;
612 }
613
614 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
615 SLOGE("Error reading persistent data before save");
616 goto err2;
617 }
618
619 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
620 /* The first copy is the curent valid copy, so write to
621 * the second copy and erase this one */
622 write_offset = crypt_ftr.persist_data_offset[1];
623 erase_offset = crypt_ftr.persist_data_offset[0];
624 } else {
625 /* The second copy must be the valid copy, so write to
626 * the first copy, and erase the second */
627 write_offset = crypt_ftr.persist_data_offset[0];
628 erase_offset = crypt_ftr.persist_data_offset[1];
629 }
630
631 /* Write the new copy first, if successful, then erase the old copy */
632 if (lseek(fd, write_offset, SEEK_SET) < 0) {
633 SLOGE("Cannot seek to write persistent data");
634 goto err2;
635 }
636 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
637 (int) crypt_ftr.persist_data_size) {
638 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
639 SLOGE("Cannot seek to erase previous persistent data");
640 goto err2;
641 }
642 fsync(fd);
643 memset(pdata, 0, crypt_ftr.persist_data_size);
644 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
645 (int) crypt_ftr.persist_data_size) {
646 SLOGE("Cannot write to erase previous persistent data");
647 goto err2;
648 }
649 fsync(fd);
650 } else {
651 SLOGE("Cannot write to save persistent data");
652 goto err2;
653 }
654
655 /* Success */
656 free(pdata);
657 close(fd);
658 return 0;
659
660err2:
661 free(pdata);
662err:
663 close(fd);
664 return -1;
665}
666
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800667/* Convert a binary key of specified length into an ascii hex string equivalent,
668 * without the leading 0x and with null termination
669 */
670void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
671 char *master_key_ascii)
672{
673 unsigned int i, a;
674 unsigned char nibble;
675
676 for (i=0, a=0; i<keysize; i++, a+=2) {
677 /* For each byte, write out two ascii hex digits */
678 nibble = (master_key[i] >> 4) & 0xf;
679 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
680
681 nibble = master_key[i] & 0xf;
682 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
683 }
684
685 /* Add the null termination */
686 master_key_ascii[a] = '\0';
687
688}
689
Ken Sumralldb5e0262013-02-05 17:39:48 -0800690static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
691 char *real_blk_name, const char *name, int fd,
692 char *extra_params)
693{
694 char buffer[DM_CRYPT_BUF_SIZE];
695 struct dm_ioctl *io;
696 struct dm_target_spec *tgt;
697 char *crypt_params;
698 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
699 int i;
700
701 io = (struct dm_ioctl *) buffer;
702
703 /* Load the mapping table for this device */
704 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
705
706 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
707 io->target_count = 1;
708 tgt->status = 0;
709 tgt->sector_start = 0;
710 tgt->length = crypt_ftr->fs_size;
711 strcpy(tgt->target_type, "crypt");
712
713 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
714 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
715 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
716 master_key_ascii, real_blk_name, extra_params);
717 crypt_params += strlen(crypt_params) + 1;
718 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
719 tgt->next = crypt_params - buffer;
720
721 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
722 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
723 break;
724 }
725 usleep(500000);
726 }
727
728 if (i == TABLE_LOAD_RETRIES) {
729 /* We failed to load the table, return an error */
730 return -1;
731 } else {
732 return i + 1;
733 }
734}
735
736
737static int get_dm_crypt_version(int fd, const char *name, int *version)
738{
739 char buffer[DM_CRYPT_BUF_SIZE];
740 struct dm_ioctl *io;
741 struct dm_target_versions *v;
742 int i;
743
744 io = (struct dm_ioctl *) buffer;
745
746 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
747
748 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
749 return -1;
750 }
751
752 /* Iterate over the returned versions, looking for name of "crypt".
753 * When found, get and return the version.
754 */
755 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
756 while (v->next) {
757 if (! strcmp(v->name, "crypt")) {
758 /* We found the crypt driver, return the version, and get out */
759 version[0] = v->version[0];
760 version[1] = v->version[1];
761 version[2] = v->version[2];
762 return 0;
763 }
764 v = (struct dm_target_versions *)(((char *)v) + v->next);
765 }
766
767 return -1;
768}
769
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800770static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -0700771 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800772{
773 char buffer[DM_CRYPT_BUF_SIZE];
774 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
775 char *crypt_params;
776 struct dm_ioctl *io;
777 struct dm_target_spec *tgt;
778 unsigned int minor;
779 int fd;
Ken Sumralle919efe2012-09-29 17:07:41 -0700780 int i;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800781 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800782 int version[3];
783 char *extra_params;
784 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800785
786 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
787 SLOGE("Cannot open device-mapper\n");
788 goto errout;
789 }
790
791 io = (struct dm_ioctl *) buffer;
792
793 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
794 if (ioctl(fd, DM_DEV_CREATE, io)) {
795 SLOGE("Cannot create dm-crypt device\n");
796 goto errout;
797 }
798
799 /* Get the device status, in particular, the name of it's device file */
800 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
801 if (ioctl(fd, DM_DEV_STATUS, io)) {
802 SLOGE("Cannot retrieve dm-crypt device status\n");
803 goto errout;
804 }
805 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
806 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
807
Ken Sumralldb5e0262013-02-05 17:39:48 -0800808 extra_params = "";
809 if (! get_dm_crypt_version(fd, name, version)) {
810 /* Support for allow_discards was added in version 1.11.0 */
811 if ((version[0] >= 2) ||
812 ((version[0] == 1) && (version[1] >= 11))) {
813 extra_params = "1 allow_discards";
814 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
815 }
Ken Sumralle919efe2012-09-29 17:07:41 -0700816 }
817
Ken Sumralldb5e0262013-02-05 17:39:48 -0800818 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
819 fd, extra_params);
820 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800821 SLOGE("Cannot load dm-crypt mapping table.\n");
822 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800823 } else if (load_count > 1) {
824 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800825 }
826
827 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -0800828 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800829
830 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
831 SLOGE("Cannot resume the dm-crypt device\n");
832 goto errout;
833 }
834
835 /* We made it here with no errors. Woot! */
836 retval = 0;
837
838errout:
839 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
840
841 return retval;
842}
843
Ken Sumrall29d8da82011-05-18 17:20:07 -0700844static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800845{
846 int fd;
847 char buffer[DM_CRYPT_BUF_SIZE];
848 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800849 int retval = -1;
850
851 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
852 SLOGE("Cannot open device-mapper\n");
853 goto errout;
854 }
855
856 io = (struct dm_ioctl *) buffer;
857
858 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
859 if (ioctl(fd, DM_DEV_REMOVE, io)) {
860 SLOGE("Cannot remove dm-crypt device\n");
861 goto errout;
862 }
863
864 /* We made it here with no errors. Woot! */
865 retval = 0;
866
867errout:
868 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
869
870 return retval;
871
872}
873
Mark Salyzyn5eecc442014-02-12 14:16:14 -0800874static void pbkdf2(char *passwd, unsigned char *salt, unsigned char *ikey, void *params UNUSED) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800875 /* Turn the password into a key and IV that can decrypt the master key */
Ken Sumralle8744072011-01-18 22:01:55 -0800876 PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800877 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800878}
879
Kenny Rootc4c70f12013-06-14 12:11:38 -0700880static void scrypt(char *passwd, unsigned char *salt, unsigned char *ikey, void *params) {
881 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
882
883 int N = 1 << ftr->N_factor;
884 int r = 1 << ftr->r_factor;
885 int p = 1 << ftr->p_factor;
886
887 /* Turn the password into a key and IV that can decrypt the master key */
888 crypto_scrypt((unsigned char *) passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
889 KEY_LEN_BYTES + IV_LEN_BYTES);
890}
891
Ken Sumralle8744072011-01-18 22:01:55 -0800892static int encrypt_master_key(char *passwd, unsigned char *salt,
893 unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700894 unsigned char *encrypted_master_key,
895 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800896{
897 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
898 EVP_CIPHER_CTX e_ctx;
899 int encrypted_len, final_len;
900
901 /* Turn the password into a key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700902 get_device_scrypt_params(crypt_ftr);
903 scrypt(passwd, salt, ikey, crypt_ftr);
904
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800905 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -0700906 EVP_CIPHER_CTX_init(&e_ctx);
907 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800908 SLOGE("EVP_EncryptInit failed\n");
909 return -1;
910 }
911 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800912
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800913 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800914 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
915 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800916 SLOGE("EVP_EncryptUpdate failed\n");
917 return -1;
918 }
Adam Langley889c4f12014-09-03 14:23:13 -0700919 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800920 SLOGE("EVP_EncryptFinal failed\n");
921 return -1;
922 }
923
924 if (encrypted_len + final_len != KEY_LEN_BYTES) {
925 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
926 return -1;
927 } else {
928 return 0;
929 }
930}
931
JP Abgrall7bdfa522013-11-15 13:42:56 -0800932static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
Ken Sumralle8744072011-01-18 22:01:55 -0800933 unsigned char *encrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700934 unsigned char *decrypted_master_key,
935 kdf_func kdf, void *kdf_params)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800936{
937 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 -0800938 EVP_CIPHER_CTX d_ctx;
939 int decrypted_len, final_len;
940
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800941 /* Turn the password into a key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700942 kdf(passwd, salt, ikey, kdf_params);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800943
944 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -0700945 EVP_CIPHER_CTX_init(&d_ctx);
946 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800947 return -1;
948 }
949 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
950 /* Decrypt the master key */
951 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
952 encrypted_master_key, KEY_LEN_BYTES)) {
953 return -1;
954 }
Adam Langley889c4f12014-09-03 14:23:13 -0700955 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800956 return -1;
957 }
958
959 if (decrypted_len + final_len != KEY_LEN_BYTES) {
960 return -1;
961 } else {
962 return 0;
963 }
964}
965
Kenny Rootc4c70f12013-06-14 12:11:38 -0700966static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800967{
Kenny Rootc4c70f12013-06-14 12:11:38 -0700968 if (ftr->kdf_type == KDF_SCRYPT) {
969 *kdf = scrypt;
970 *kdf_params = ftr;
971 } else {
972 *kdf = pbkdf2;
973 *kdf_params = NULL;
974 }
975}
976
JP Abgrall7bdfa522013-11-15 13:42:56 -0800977static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700978 struct crypt_mnt_ftr *crypt_ftr)
979{
980 kdf_func kdf;
981 void *kdf_params;
982 int ret;
983
984 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
JP Abgrall7bdfa522013-11-15 13:42:56 -0800985 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, decrypted_master_key, kdf,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700986 kdf_params);
987 if (ret != 0) {
988 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -0700989 }
990
991 return ret;
992}
993
994static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
995 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800996 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -0800997 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800998 EVP_CIPHER_CTX e_ctx;
999 int encrypted_len, final_len;
1000
1001 /* Get some random bits for a key */
1002 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001003 read(fd, key_buf, sizeof(key_buf));
1004 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001005 close(fd);
1006
1007 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001008 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001009}
1010
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001011static int wait_and_unmount(char *mountpoint)
1012{
1013 int i, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001014#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001015
1016 /* Now umount the tmpfs filesystem */
1017 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
1018 if (umount(mountpoint)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001019 if (errno == EINVAL) {
1020 /* EINVAL is returned if the directory is not a mountpoint,
1021 * i.e. there is no filesystem mounted there. So just get out.
1022 */
1023 break;
1024 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001025 sleep(1);
1026 i++;
1027 } else {
1028 break;
1029 }
1030 }
1031
1032 if (i < WAIT_UNMOUNT_COUNT) {
1033 SLOGD("unmounting %s succeeded\n", mountpoint);
1034 rc = 0;
1035 } else {
1036 SLOGE("unmounting %s failed\n", mountpoint);
1037 rc = -1;
1038 }
1039
1040 return rc;
1041}
1042
Ken Sumrallc5872692013-05-14 15:26:31 -07001043#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001044static int prep_data_fs(void)
1045{
1046 int i;
1047
1048 /* Do the prep of the /data filesystem */
1049 property_set("vold.post_fs_data_done", "0");
1050 property_set("vold.decrypt", "trigger_post_fs_data");
1051 SLOGD("Just triggered post_fs_data\n");
1052
Ken Sumrallc5872692013-05-14 15:26:31 -07001053 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001054 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001055 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001056
1057 property_get("vold.post_fs_data_done", p, "0");
1058 if (*p == '1') {
1059 break;
1060 } else {
1061 usleep(250000);
1062 }
1063 }
1064 if (i == DATA_PREP_TIMEOUT) {
1065 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001066 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001067 return -1;
1068 } else {
1069 SLOGD("post_fs_data done\n");
1070 return 0;
1071 }
1072}
1073
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001074int cryptfs_restart(void)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001075{
1076 char fs_type[32];
1077 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001078 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001079 char fs_options[256];
1080 unsigned long mnt_flags;
1081 struct stat statbuf;
1082 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001083 static int restart_successful = 0;
1084
1085 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001086 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001087 SLOGE("Encrypted filesystem not validated, aborting");
1088 return -1;
1089 }
1090
1091 if (restart_successful) {
1092 SLOGE("System already restarted with encrypted disk, aborting");
1093 return -1;
1094 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001095
1096 /* Here is where we shut down the framework. The init scripts
1097 * start all services in one of three classes: core, main or late_start.
1098 * On boot, we start core and main. Now, we stop main, but not core,
1099 * as core includes vold and a few other really important things that
1100 * we need to keep running. Once main has stopped, we should be able
1101 * to umount the tmpfs /data, then mount the encrypted /data.
1102 * We then restart the class main, and also the class late_start.
1103 * At the moment, I've only put a few things in late_start that I know
1104 * are not needed to bring up the framework, and that also cause problems
1105 * with unmounting the tmpfs /data, but I hope to add add more services
1106 * to the late_start class as we optimize this to decrease the delay
1107 * till the user is asked for the password to the filesystem.
1108 */
1109
1110 /* The init files are setup to stop the class main when vold.decrypt is
1111 * set to trigger_reset_main.
1112 */
1113 property_set("vold.decrypt", "trigger_reset_main");
1114 SLOGD("Just asked init to shut down class main\n");
1115
Ken Sumrall92736ef2012-10-17 20:57:14 -07001116 /* Ugh, shutting down the framework is not synchronous, so until it
1117 * can be fixed, this horrible hack will wait a moment for it all to
1118 * shut down before proceeding. Without it, some devices cannot
1119 * restart the graphics services.
1120 */
1121 sleep(2);
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001122
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001123 /* Now that the framework is shutdown, we should be able to umount()
1124 * the tmpfs filesystem, and mount the real one.
1125 */
1126
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001127 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1128 if (strlen(crypto_blkdev) == 0) {
1129 SLOGE("fs_crypto_blkdev not set\n");
1130 return -1;
1131 }
1132
Ken Sumralle5032c42012-04-01 23:58:44 -07001133 if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
1134 /* If that succeeded, then mount the decrypted filesystem */
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001135 fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001136
Ken Sumralle5032c42012-04-01 23:58:44 -07001137 property_set("vold.decrypt", "trigger_load_persist_props");
1138 /* Create necessary paths on /data */
1139 if (prep_data_fs()) {
1140 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001141 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001142
1143 /* startup service classes main and late_start */
1144 property_set("vold.decrypt", "trigger_restart_framework");
1145 SLOGD("Just triggered restart_framework\n");
1146
1147 /* Give it a few moments to get started */
1148 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001149 }
1150
Ken Sumrall0cc16632011-01-18 20:32:26 -08001151 if (rc == 0) {
1152 restart_successful = 1;
1153 }
1154
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001155 return rc;
1156}
1157
Mark Salyzyn5eecc442014-02-12 14:16:14 -08001158static int do_crypto_complete(char *mount_point UNUSED)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001159{
1160 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001161 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001162 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001163
1164 property_get("ro.crypto.state", encrypted_state, "");
1165 if (strcmp(encrypted_state, "encrypted") ) {
1166 SLOGE("not running with encryption, aborting");
1167 return 1;
1168 }
1169
Ken Sumrall160b4d62013-04-22 12:15:39 -07001170 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001171 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001172
Ken Sumralle1a45852011-12-14 21:24:27 -08001173 /*
1174 * Only report this error if key_loc is a file and it exists.
1175 * If the device was never encrypted, and /data is not mountable for
1176 * some reason, returning 1 should prevent the UI from presenting the
1177 * a "enter password" screen, or worse, a "press button to wipe the
1178 * device" screen.
1179 */
1180 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1181 SLOGE("master key file does not exist, aborting");
1182 return 1;
1183 } else {
1184 SLOGE("Error getting crypt footer and key\n");
1185 return -1;
1186 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001187 }
1188
1189 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1190 SLOGE("Encryption process didn't finish successfully\n");
1191 return -2; /* -2 is the clue to the UI that there is no usable data on the disk,
1192 * and give the user an option to wipe the disk */
1193 }
1194
1195 /* We passed the test! We shall diminish, and return to the west */
1196 return 0;
1197}
1198
Ken Sumrall29d8da82011-05-18 17:20:07 -07001199static int test_mount_encrypted_fs(char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001200{
1201 struct crypt_mnt_ftr crypt_ftr;
1202 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001203 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001204 char crypto_blkdev[MAXPATHLEN];
1205 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001206 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001207 unsigned int orig_failed_decrypt_count;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001208 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001209 int rc;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001210 kdf_func kdf;
1211 void *kdf_params;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001212
Ken Sumrall0cc16632011-01-18 20:32:26 -08001213 property_get("ro.crypto.state", encrypted_state, "");
Jason parks70a4b3f2011-01-28 10:10:47 -06001214 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001215 SLOGE("encrypted fs already validated or not running with encryption, aborting");
1216 return -1;
1217 }
1218
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001219 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001220
Ken Sumrall160b4d62013-04-22 12:15:39 -07001221 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001222 SLOGE("Error getting crypt footer and key\n");
1223 return -1;
1224 }
Ken Sumralld33d4172011-02-01 00:49:13 -08001225
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001226 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr.fs_size);
1227 orig_failed_decrypt_count = crypt_ftr.failed_decrypt_count;
1228
1229 if (! (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001230 if (decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr)) {
1231 SLOGE("Failed to decrypt master key\n");
1232 return -1;
1233 }
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;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001283 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001284 rc = 0;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001285 /*
1286 * Upgrade if we're not using the latest KDF.
1287 */
1288 if (crypt_ftr.kdf_type != KDF_SCRYPT) {
1289 crypt_ftr.kdf_type = KDF_SCRYPT;
1290 rc = encrypt_master_key(passwd, crypt_ftr.salt, saved_master_key, crypt_ftr.master_key,
1291 &crypt_ftr);
1292 if (!rc) {
1293 rc = put_crypt_ftr_and_key(&crypt_ftr);
1294 }
1295 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1296 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001297 }
1298
1299 return rc;
1300}
1301
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001302/* Called by vold when it wants to undo the crypto mapping of a volume it
1303 * manages. This is usually in response to a factory reset, when we want
1304 * to undo the crypto mapping so the volume is formatted in the clear.
1305 */
1306int cryptfs_revert_volume(const char *label)
1307{
1308 return delete_crypto_blk_dev((char *)label);
1309}
1310
Ken Sumrall29d8da82011-05-18 17:20:07 -07001311/*
1312 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1313 * Setup a dm-crypt mapping, use the saved master key from
1314 * setting up the /data mapping, and return the new device path.
1315 */
1316int cryptfs_setup_volume(const char *label, int major, int minor,
1317 char *crypto_sys_path, unsigned int max_path,
1318 int *new_major, int *new_minor)
1319{
1320 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1321 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001322 struct stat statbuf;
1323 int nr_sec, fd;
1324
1325 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1326
Ken Sumrall160b4d62013-04-22 12:15:39 -07001327 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001328
1329 /* Update the fs_size field to be the size of the volume */
1330 fd = open(real_blkdev, O_RDONLY);
1331 nr_sec = get_blkdev_size(fd);
1332 close(fd);
1333 if (nr_sec == 0) {
1334 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1335 return -1;
1336 }
1337
1338 sd_crypt_ftr.fs_size = nr_sec;
1339 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1340 crypto_blkdev, label);
1341
1342 stat(crypto_blkdev, &statbuf);
1343 *new_major = MAJOR(statbuf.st_rdev);
1344 *new_minor = MINOR(statbuf.st_rdev);
1345
1346 /* Create path to sys entry for this block device */
1347 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1348
1349 return 0;
1350}
1351
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001352int cryptfs_crypto_complete(void)
1353{
1354 return do_crypto_complete("/data");
1355}
1356
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001357int cryptfs_check_passwd(char *passwd)
1358{
1359 int rc = -1;
1360
Ken Sumrall29d8da82011-05-18 17:20:07 -07001361 rc = test_mount_encrypted_fs(passwd, DATA_MNT_POINT, "userdata");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001362
1363 return rc;
1364}
1365
Ken Sumrall3ad90722011-10-04 20:38:29 -07001366int cryptfs_verify_passwd(char *passwd)
1367{
1368 struct crypt_mnt_ftr crypt_ftr;
1369 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001370 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001371 char encrypted_state[PROPERTY_VALUE_MAX];
1372 int rc;
1373
1374 property_get("ro.crypto.state", encrypted_state, "");
1375 if (strcmp(encrypted_state, "encrypted") ) {
1376 SLOGE("device not encrypted, aborting");
1377 return -2;
1378 }
1379
1380 if (!master_key_saved) {
1381 SLOGE("encrypted fs not yet mounted, aborting");
1382 return -1;
1383 }
1384
1385 if (!saved_mount_point) {
1386 SLOGE("encrypted fs failed to save mount point, aborting");
1387 return -1;
1388 }
1389
Ken Sumrall160b4d62013-04-22 12:15:39 -07001390 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001391 SLOGE("Error getting crypt footer and key\n");
1392 return -1;
1393 }
1394
1395 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1396 /* If the device has no password, then just say the password is valid */
1397 rc = 0;
1398 } else {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001399 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001400 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1401 /* They match, the password is correct */
1402 rc = 0;
1403 } else {
1404 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1405 sleep(1);
1406 rc = 1;
1407 }
1408 }
1409
1410 return rc;
1411}
1412
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001413/* Initialize a crypt_mnt_ftr structure. The keysize is
1414 * defaulted to 16 bytes, and the filesystem size to 0.
1415 * Presumably, at a minimum, the caller will update the
1416 * filesystem size and crypto_type_name after calling this function.
1417 */
1418static void cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
1419{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001420 off64_t off;
1421
1422 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001423 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001424 ftr->major_version = CURRENT_MAJOR_VERSION;
1425 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001426 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001427 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001428
Kenny Rootc4c70f12013-06-14 12:11:38 -07001429 ftr->kdf_type = KDF_SCRYPT;
1430 get_device_scrypt_params(ftr);
1431
Ken Sumrall160b4d62013-04-22 12:15:39 -07001432 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1433 if (get_crypt_ftr_info(NULL, &off) == 0) {
1434 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1435 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1436 ftr->persist_data_size;
1437 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001438}
1439
Ken Sumrall29d8da82011-05-18 17:20:07 -07001440static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001441{
Ken Sumralle550f782013-08-20 13:48:23 -07001442 const char *args[10];
1443 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1444 int num_args;
1445 int status;
1446 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001447 int rc = -1;
1448
Ken Sumrall29d8da82011-05-18 17:20:07 -07001449 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001450 args[0] = "/system/bin/make_ext4fs";
1451 args[1] = "-a";
1452 args[2] = "/data";
1453 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07001454 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07001455 args[4] = size_str;
1456 args[5] = crypto_blkdev;
1457 num_args = 6;
1458 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1459 args[0], args[1], args[2], args[3], args[4], args[5]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001460 } else if (type== FAT_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001461 args[0] = "/system/bin/newfs_msdos";
1462 args[1] = "-F";
1463 args[2] = "32";
1464 args[3] = "-O";
1465 args[4] = "android";
1466 args[5] = "-c";
1467 args[6] = "8";
1468 args[7] = "-s";
Elliott Hughes73737162014-06-25 17:27:42 -07001469 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
Ken Sumralle550f782013-08-20 13:48:23 -07001470 args[8] = size_str;
1471 args[9] = crypto_blkdev;
1472 num_args = 10;
1473 SLOGI("Making empty filesystem with command %s %s %s %s %s %s %s %s %s %s\n",
1474 args[0], args[1], args[2], args[3], args[4], args[5],
1475 args[6], args[7], args[8], args[9]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001476 } else {
1477 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1478 return -1;
1479 }
1480
Ken Sumralle550f782013-08-20 13:48:23 -07001481 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1482
1483 if (tmp != 0) {
1484 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001485 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07001486 if (WIFEXITED(status)) {
1487 if (WEXITSTATUS(status)) {
1488 SLOGE("Error creating filesystem on %s, exit status %d ",
1489 crypto_blkdev, WEXITSTATUS(status));
1490 } else {
1491 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
1492 rc = 0;
1493 }
1494 } else {
1495 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
1496 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001497 }
1498
1499 return rc;
1500}
1501
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001502#define CRYPT_INPLACE_BUFSIZE 4096
1503#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / 512)
Ken Sumrall29d8da82011-05-18 17:20:07 -07001504static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev, off64_t size,
1505 off64_t *size_already_done, off64_t tot_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001506{
1507 int realfd, cryptofd;
1508 char *buf[CRYPT_INPLACE_BUFSIZE];
1509 int rc = -1;
1510 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001511 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001512 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001513
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001514 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
1515 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
1516 return -1;
1517 }
1518
1519 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
1520 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1521 close(realfd);
1522 return -1;
1523 }
1524
1525 /* This is pretty much a simple loop of reading 4K, and writing 4K.
1526 * The size passed in is the number of 512 byte sectors in the filesystem.
1527 * So compute the number of whole 4K blocks we should read/write,
1528 * and the remainder.
1529 */
1530 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
1531 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001532 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
1533 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001534
1535 SLOGE("Encrypting filesystem in place...");
1536
Ken Sumrall29d8da82011-05-18 17:20:07 -07001537 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001538 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001539 /* process the majority of the filesystem in blocks */
1540 for (i=0; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001541 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001542 if (new_pct > cur_pct) {
1543 char buf[8];
1544
1545 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07001546 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001547 property_set("vold.encrypt_progress", buf);
1548 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001549 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1550 SLOGE("Error reading real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1551 goto errout;
1552 }
1553 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1554 SLOGE("Error writing crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1555 goto errout;
1556 }
1557 }
1558
1559 /* Do any remaining sectors */
1560 for (i=0; i<remainder; i++) {
1561 if (unix_read(realfd, buf, 512) <= 0) {
1562 SLOGE("Error reading rival sectors from real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1563 goto errout;
1564 }
1565 if (unix_write(cryptofd, buf, 512) <= 0) {
1566 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1567 goto errout;
1568 }
1569 }
1570
Ken Sumrall29d8da82011-05-18 17:20:07 -07001571 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001572 rc = 0;
1573
1574errout:
1575 close(realfd);
1576 close(cryptofd);
1577
1578 return rc;
1579}
1580
1581#define CRYPTO_ENABLE_WIPE 1
1582#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001583
1584#define FRAMEWORK_BOOT_WAIT 60
1585
Ken Sumrall29d8da82011-05-18 17:20:07 -07001586static inline int should_encrypt(struct volume_info *volume)
1587{
1588 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
1589 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
1590}
1591
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001592int cryptfs_enable(char *howarg, char *passwd)
1593{
1594 int how = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001595 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN], sd_crypto_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07001596 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001597 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07001598 int rc=-1, fd, i, ret;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001599 struct crypt_mnt_ftr crypt_ftr, sd_crypt_ftr;;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001600 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001601 char tmpfs_options[PROPERTY_VALUE_MAX];
1602 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001603 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07001604 char key_loc[PROPERTY_VALUE_MAX];
1605 char fuse_sdcard[PROPERTY_VALUE_MAX];
1606 char *sd_mnt_point;
1607 char sd_blk_dev[256] = { 0 };
1608 int num_vols;
1609 struct volume_info *vol_list = 0;
1610 off64_t cur_encryption_done=0, tot_encryption_size=0;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001611
1612 property_get("ro.crypto.state", encrypted_state, "");
1613 if (strcmp(encrypted_state, "unencrypted")) {
1614 SLOGE("Device is already running encrypted, aborting");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001615 goto error_unencrypted;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001616 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001617
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001618 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001619
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001620 if (!strcmp(howarg, "wipe")) {
1621 how = CRYPTO_ENABLE_WIPE;
1622 } else if (! strcmp(howarg, "inplace")) {
1623 how = CRYPTO_ENABLE_INPLACE;
1624 } else {
1625 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08001626 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001627 }
1628
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001629 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001630
Ken Sumrall3ed82362011-01-28 23:31:16 -08001631 /* Get the size of the real block device */
1632 fd = open(real_blkdev, O_RDONLY);
1633 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
1634 SLOGE("Cannot get size of block device %s\n", real_blkdev);
1635 goto error_unencrypted;
1636 }
1637 close(fd);
1638
1639 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001640 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001641 unsigned int fs_size_sec, max_fs_size_sec;
1642
1643 fs_size_sec = get_fs_size(real_blkdev);
1644 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1645
1646 if (fs_size_sec > max_fs_size_sec) {
1647 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
1648 goto error_unencrypted;
1649 }
1650 }
1651
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001652 /* Get a wakelock as this may take a while, and we don't want the
1653 * device to sleep on us. We'll grab a partial wakelock, and if the UI
1654 * wants to keep the screen on, it can grab a full wakelock.
1655 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001656 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001657 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
1658
Jeff Sharkey7382f812012-08-23 14:08:59 -07001659 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07001660 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07001661 if (!sd_mnt_point) {
1662 sd_mnt_point = getenv("EXTERNAL_STORAGE");
1663 }
1664 if (!sd_mnt_point) {
1665 sd_mnt_point = "/mnt/sdcard";
1666 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07001667
1668 num_vols=vold_getNumDirectVolumes();
1669 vol_list = malloc(sizeof(struct volume_info) * num_vols);
1670 vold_getDirectVolumeList(vol_list);
1671
1672 for (i=0; i<num_vols; i++) {
1673 if (should_encrypt(&vol_list[i])) {
1674 fd = open(vol_list[i].blk_dev, O_RDONLY);
1675 if ( (vol_list[i].size = get_blkdev_size(fd)) == 0) {
1676 SLOGE("Cannot get size of block device %s\n", vol_list[i].blk_dev);
1677 goto error_unencrypted;
1678 }
1679 close(fd);
1680
Ken Sumrall3b170052011-07-11 15:38:57 -07001681 ret=vold_disableVol(vol_list[i].label);
Ken Sumrall319b1042011-06-14 14:01:55 -07001682 if ((ret < 0) && (ret != UNMOUNT_NOT_MOUNTED_ERR)) {
1683 /* -2 is returned when the device exists but is not currently mounted.
1684 * ignore the error and continue. */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001685 SLOGE("Failed to unmount volume %s\n", vol_list[i].label);
1686 goto error_unencrypted;
1687 }
1688 }
1689 }
1690
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001691 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001692 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001693 */
1694 property_set("vold.decrypt", "trigger_shutdown_framework");
1695 SLOGD("Just asked init to shut down class main\n");
1696
Ken Sumrall425524d2012-06-14 20:55:28 -07001697 if (vold_unmountAllAsecs()) {
1698 /* Just report the error. If any are left mounted,
1699 * umounting /data below will fail and handle the error.
1700 */
1701 SLOGE("Error unmounting internal asecs");
1702 }
1703
Ken Sumrall29d8da82011-05-18 17:20:07 -07001704 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
1705 if (!strcmp(fuse_sdcard, "true")) {
1706 /* This is a device using the fuse layer to emulate the sdcard semantics
1707 * on top of the userdata partition. vold does not manage it, it is managed
1708 * by the sdcard service. The sdcard service was killed by the property trigger
1709 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
1710 * unlike the case for vold managed devices above.
1711 */
1712 if (wait_and_unmount(sd_mnt_point)) {
1713 goto error_shutting_down;
1714 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001715 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001716
1717 /* Now unmount the /data partition. */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001718 if (wait_and_unmount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001719 goto error_shutting_down;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001720 }
1721
1722 /* Do extra work for a better UX when doing the long inplace encryption */
1723 if (how == CRYPTO_ENABLE_INPLACE) {
1724 /* Now that /data is unmounted, we need to mount a tmpfs
1725 * /data, set a property saying we're doing inplace encryption,
1726 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001727 */
Ken Sumralle5032c42012-04-01 23:58:44 -07001728 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001729 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001730 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001731 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08001732 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001733
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001734 /* restart the framework. */
1735 /* Create necessary paths on /data */
1736 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001737 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001738 }
1739
Ken Sumrall92736ef2012-10-17 20:57:14 -07001740 /* Ugh, shutting down the framework is not synchronous, so until it
1741 * can be fixed, this horrible hack will wait a moment for it all to
1742 * shut down before proceeding. Without it, some devices cannot
1743 * restart the graphics services.
1744 */
1745 sleep(2);
1746
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001747 /* startup service classes main and late_start */
1748 property_set("vold.decrypt", "trigger_restart_min_framework");
1749 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001750
Ken Sumrall7df84122011-01-18 14:04:08 -08001751 /* OK, the framework is restarted and will soon be showing a
1752 * progress bar. Time to setup an encrypted mapping, and
1753 * either write a new filesystem, or encrypt in place updating
1754 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001755 */
1756 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001757
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001758 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001759 /* Initialize a crypt_mnt_ftr for the partition */
1760 cryptfs_init_crypt_mnt_ftr(&crypt_ftr);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001761
Ken Sumrall29d8da82011-05-18 17:20:07 -07001762 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
1763 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1764 } else {
1765 crypt_ftr.fs_size = nr_sec;
1766 }
Ken Sumralld33d4172011-02-01 00:49:13 -08001767 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001768 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
1769
1770 /* Make an encrypted master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001771 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001772 SLOGE("Cannot create encrypted master key\n");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001773 goto error_unencrypted;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001774 }
1775
1776 /* Write the key to the end of the partition */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001777 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001778
Ken Sumrall160b4d62013-04-22 12:15:39 -07001779 /* If any persistent data has been remembered, save it.
1780 * If none, create a valid empty table and save that.
1781 */
1782 if (!persist_data) {
1783 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
1784 if (pdata) {
1785 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
1786 persist_data = pdata;
1787 }
1788 }
1789 if (persist_data) {
1790 save_persistent_data();
1791 }
1792
JP Abgrall7bdfa522013-11-15 13:42:56 -08001793 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001794 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
1795 "userdata");
1796
Ken Sumrall128626f2011-06-28 18:45:14 -07001797 /* The size of the userdata partition, and add in the vold volumes below */
1798 tot_encryption_size = crypt_ftr.fs_size;
1799
Ken Sumrall29d8da82011-05-18 17:20:07 -07001800 /* setup crypto mapping for all encryptable volumes handled by vold */
1801 for (i=0; i<num_vols; i++) {
1802 if (should_encrypt(&vol_list[i])) {
1803 vol_list[i].crypt_ftr = crypt_ftr; /* gotta love struct assign */
1804 vol_list[i].crypt_ftr.fs_size = vol_list[i].size;
1805 create_crypto_blk_dev(&vol_list[i].crypt_ftr, decrypted_master_key,
1806 vol_list[i].blk_dev, vol_list[i].crypto_blkdev,
1807 vol_list[i].label);
Ken Sumrall128626f2011-06-28 18:45:14 -07001808 tot_encryption_size += vol_list[i].size;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001809 }
1810 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001811
1812 if (how == CRYPTO_ENABLE_WIPE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001813 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr.fs_size, EXT4_FS);
1814 /* Encrypt all encryptable volumes handled by vold */
1815 if (!rc) {
1816 for (i=0; i<num_vols; i++) {
1817 if (should_encrypt(&vol_list[i])) {
1818 rc = cryptfs_enable_wipe(vol_list[i].crypto_blkdev,
1819 vol_list[i].crypt_ftr.fs_size, FAT_FS);
1820 }
1821 }
1822 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001823 } else if (how == CRYPTO_ENABLE_INPLACE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001824 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr.fs_size,
1825 &cur_encryption_done, tot_encryption_size);
1826 /* Encrypt all encryptable volumes handled by vold */
1827 if (!rc) {
1828 for (i=0; i<num_vols; i++) {
1829 if (should_encrypt(&vol_list[i])) {
1830 rc = cryptfs_enable_inplace(vol_list[i].crypto_blkdev,
1831 vol_list[i].blk_dev,
1832 vol_list[i].crypt_ftr.fs_size,
1833 &cur_encryption_done, tot_encryption_size);
1834 }
1835 }
1836 }
1837 if (!rc) {
1838 /* The inplace routine never actually sets the progress to 100%
1839 * due to the round down nature of integer division, so set it here */
1840 property_set("vold.encrypt_progress", "100");
1841 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001842 } else {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001843 /* Shouldn't happen */
1844 SLOGE("cryptfs_enable: internal error, unknown option\n");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001845 goto error_unencrypted;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001846 }
1847
1848 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001849 delete_crypto_blk_dev("userdata");
1850 for (i=0; i<num_vols; i++) {
1851 if (should_encrypt(&vol_list[i])) {
1852 delete_crypto_blk_dev(vol_list[i].label);
1853 }
1854 }
1855
1856 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001857
1858 if (! rc) {
1859 /* Success */
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001860
Ken Sumralld33d4172011-02-01 00:49:13 -08001861 /* Clear the encryption in progres flag in the footer */
1862 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001863 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08001864
Ken Sumrall29d8da82011-05-18 17:20:07 -07001865 sleep(2); /* Give the UI a chance to show 100% progress */
Ken Sumralladfba362013-06-04 16:37:52 -07001866 cryptfs_reboot(0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001867 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001868 char value[PROPERTY_VALUE_MAX];
1869
Ken Sumrall319369a2012-06-27 16:30:18 -07001870 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001871 if (!strcmp(value, "1")) {
1872 /* wipe data if encryption failed */
1873 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
1874 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07001875 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001876 if (fd >= 0) {
1877 write(fd, "--wipe_data", strlen("--wipe_data") + 1);
1878 close(fd);
1879 } else {
1880 SLOGE("could not open /cache/recovery/command\n");
1881 }
Ken Sumralladfba362013-06-04 16:37:52 -07001882 cryptfs_reboot(1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08001883 } else {
1884 /* set property to trigger dialog */
1885 property_set("vold.encrypt_progress", "error_partially_encrypted");
1886 release_wake_lock(lockid);
1887 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001888 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001889 }
1890
Ken Sumrall3ed82362011-01-28 23:31:16 -08001891 /* hrm, the encrypt step claims success, but the reboot failed.
1892 * This should not happen.
1893 * Set the property and return. Hope the framework can deal with it.
1894 */
1895 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001896 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001897 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08001898
1899error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07001900 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001901 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001902 if (lockid[0]) {
1903 release_wake_lock(lockid);
1904 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001905 return -1;
1906
1907error_shutting_down:
1908 /* we failed, and have not encrypted anthing, so the users's data is still intact,
1909 * but the framework is stopped and not restarted to show the error, so it's up to
1910 * vold to restart the system.
1911 */
1912 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Ken Sumralladfba362013-06-04 16:37:52 -07001913 cryptfs_reboot(0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08001914
1915 /* shouldn't get here */
1916 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001917 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001918 if (lockid[0]) {
1919 release_wake_lock(lockid);
1920 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08001921 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001922}
1923
Jason parks70a4b3f2011-01-28 10:10:47 -06001924int cryptfs_changepw(char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001925{
1926 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001927 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001928
1929 /* This is only allowed after we've successfully decrypted the master key */
Jason parks70a4b3f2011-01-28 10:10:47 -06001930 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001931 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001932 return -1;
1933 }
1934
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001935 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001936 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall57b63e62011-01-17 18:29:19 -08001937 SLOGE("Error getting crypt footer and key");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001938 return -1;
1939 }
1940
Kenny Rootc4c70f12013-06-14 12:11:38 -07001941 encrypt_master_key(newpw, crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001942
Jason parks70a4b3f2011-01-28 10:10:47 -06001943 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001944 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001945
1946 return 0;
1947}
Ken Sumrall160b4d62013-04-22 12:15:39 -07001948
1949static int persist_get_key(char *fieldname, char *value)
1950{
1951 unsigned int i;
1952
1953 if (persist_data == NULL) {
1954 return -1;
1955 }
1956 for (i = 0; i < persist_data->persist_valid_entries; i++) {
1957 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
1958 /* We found it! */
1959 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
1960 return 0;
1961 }
1962 }
1963
1964 return -1;
1965}
1966
1967static int persist_set_key(char *fieldname, char *value, int encrypted)
1968{
1969 unsigned int i;
1970 unsigned int num;
1971 struct crypt_mnt_ftr crypt_ftr;
1972 unsigned int max_persistent_entries;
1973 unsigned int dsize;
1974
1975 if (persist_data == NULL) {
1976 return -1;
1977 }
1978
1979 /* If encrypted, use the values from the crypt_ftr, otherwise
1980 * use the values for the current spec.
1981 */
1982 if (encrypted) {
1983 if(get_crypt_ftr_and_key(&crypt_ftr)) {
1984 return -1;
1985 }
1986 dsize = crypt_ftr.persist_data_size;
1987 } else {
1988 dsize = CRYPT_PERSIST_DATA_SIZE;
1989 }
1990 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
1991 sizeof(struct crypt_persist_entry);
1992
1993 num = persist_data->persist_valid_entries;
1994
1995 for (i = 0; i < num; i++) {
1996 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
1997 /* We found an existing entry, update it! */
1998 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
1999 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2000 return 0;
2001 }
2002 }
2003
2004 /* We didn't find it, add it to the end, if there is room */
2005 if (persist_data->persist_valid_entries < max_persistent_entries) {
2006 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2007 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2008 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2009 persist_data->persist_valid_entries++;
2010 return 0;
2011 }
2012
2013 return -1;
2014}
2015
2016/* Return the value of the specified field. */
2017int cryptfs_getfield(char *fieldname, char *value, int len)
2018{
2019 char temp_value[PROPERTY_VALUE_MAX];
2020 char real_blkdev[MAXPATHLEN];
2021 /* 0 is success, 1 is not encrypted,
2022 * -1 is value not set, -2 is any other error
2023 */
2024 int rc = -2;
2025
2026 if (persist_data == NULL) {
2027 load_persistent_data();
2028 if (persist_data == NULL) {
2029 SLOGE("Getfield error, cannot load persistent data");
2030 goto out;
2031 }
2032 }
2033
2034 if (!persist_get_key(fieldname, temp_value)) {
2035 /* We found it, copy it to the caller's buffer and return */
2036 strlcpy(value, temp_value, len);
2037 rc = 0;
2038 } else {
2039 /* Sadness, it's not there. Return the error */
2040 rc = -1;
2041 }
2042
2043out:
2044 return rc;
2045}
2046
2047/* Set the value of the specified field. */
2048int cryptfs_setfield(char *fieldname, char *value)
2049{
2050 struct crypt_persist_data stored_pdata;
2051 struct crypt_persist_data *pdata_p;
2052 struct crypt_mnt_ftr crypt_ftr;
2053 char encrypted_state[PROPERTY_VALUE_MAX];
2054 /* 0 is success, -1 is an error */
2055 int rc = -1;
2056 int encrypted = 0;
2057
2058 if (persist_data == NULL) {
2059 load_persistent_data();
2060 if (persist_data == NULL) {
2061 SLOGE("Setfield error, cannot load persistent data");
2062 goto out;
2063 }
2064 }
2065
2066 property_get("ro.crypto.state", encrypted_state, "");
2067 if (!strcmp(encrypted_state, "encrypted") ) {
2068 encrypted = 1;
2069 }
2070
2071 if (persist_set_key(fieldname, value, encrypted)) {
2072 goto out;
2073 }
2074
2075 /* If we are running encrypted, save the persistent data now */
2076 if (encrypted) {
2077 if (save_persistent_data()) {
2078 SLOGE("Setfield error, cannot save persistent data");
2079 goto out;
2080 }
2081 }
2082
2083 rc = 0;
2084
2085out:
2086 return rc;
2087}