blob: afa168e1b59a6339ae2242cced19cef1e94b31a1 [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>
Paul Lawrencef4faa572014-01-29 13:31:03 -080026#include <ctype.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080027#include <fcntl.h>
28#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"
Paul Lawrenceae59fe62014-01-21 08:23:27 -080053#include "ext4_utils.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080054
Mark Salyzyn3e971272014-01-21 13:27:04 -080055#define UNUSED __attribute__((unused))
56
Mark Salyzyn5eecc442014-02-12 14:16:14 -080057#define UNUSED __attribute__((unused))
58
Ken Sumrall8f869aa2010-12-03 03:47:09 -080059#define DM_CRYPT_BUF_SIZE 4096
60
Jason parks70a4b3f2011-01-28 10:10:47 -060061#define HASH_COUNT 2000
62#define KEY_LEN_BYTES 16
63#define IV_LEN_BYTES 16
64
Ken Sumrall29d8da82011-05-18 17:20:07 -070065#define KEY_IN_FOOTER "footer"
66
Paul Lawrencef4faa572014-01-29 13:31:03 -080067// "default_password" encoded into hex (d=0x64 etc)
68#define DEFAULT_PASSWORD "64656661756c745f70617373776f7264"
69
Ken Sumrall29d8da82011-05-18 17:20:07 -070070#define EXT4_FS 1
71#define FAT_FS 2
72
Ken Sumralle919efe2012-09-29 17:07:41 -070073#define TABLE_LOAD_RETRIES 10
74
Ken Sumrall8f869aa2010-12-03 03:47:09 -080075char *me = "cryptfs";
76
Jason parks70a4b3f2011-01-28 10:10:47 -060077static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070078static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060079static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -070080static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -080081
Paul Lawrence684dbdf2014-02-07 12:07:22 -080082/* Set when userdata is successfully decrypted and mounted.
83 * Reset whenever read (via cryptfs_just_decrypted)
84 * (Read by keyguard to avoid a double prompt.)
85 */
86static int just_decrypted = 0;
87
Ken Sumrall56ad03c2013-02-13 13:00:19 -080088extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -080089
Ken Sumralladfba362013-06-04 16:37:52 -070090static void cryptfs_reboot(int recovery)
91{
92 if (recovery) {
93 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
94 } else {
95 property_set(ANDROID_RB_PROPERTY, "reboot");
96 }
97 sleep(20);
98
99 /* Shouldn't get here, reboot should happen before sleep times out */
100 return;
101}
102
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800103static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
104{
105 memset(io, 0, dataSize);
106 io->data_size = dataSize;
107 io->data_start = sizeof(struct dm_ioctl);
108 io->version[0] = 4;
109 io->version[1] = 0;
110 io->version[2] = 0;
111 io->flags = flags;
112 if (name) {
113 strncpy(io->name, name, sizeof(io->name));
114 }
115}
116
Kenny Rootc4c70f12013-06-14 12:11:38 -0700117/**
118 * Gets the default device scrypt parameters for key derivation time tuning.
119 * The parameters should lead to about one second derivation time for the
120 * given device.
121 */
122static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
123 const int default_params[] = SCRYPT_DEFAULTS;
124 int params[] = SCRYPT_DEFAULTS;
125 char paramstr[PROPERTY_VALUE_MAX];
126 char *token;
127 char *saveptr;
128 int i;
129
130 property_get(SCRYPT_PROP, paramstr, "");
131 if (paramstr[0] != '\0') {
132 /*
133 * The token we're looking for should be three integers separated by
134 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
135 */
Kenny Root2947e342013-08-14 15:54:49 -0700136 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
137 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700138 i++, token = strtok_r(NULL, ":", &saveptr)) {
139 char *endptr;
140 params[i] = strtol(token, &endptr, 10);
141
142 /*
143 * Check that there was a valid number and it's 8-bit. If not,
144 * break out and the end check will take the default values.
145 */
146 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
147 break;
148 }
149 }
150
151 /*
152 * If there were not enough tokens or a token was malformed (not an
153 * integer), it will end up here and the default parameters can be
154 * taken.
155 */
156 if ((i != 3) || (token != NULL)) {
157 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
158 memcpy(params, default_params, sizeof(params));
159 }
160 }
161
162 ftr->N_factor = params[0];
163 ftr->r_factor = params[1];
164 ftr->p_factor = params[2];
165}
166
Ken Sumrall3ed82362011-01-28 23:31:16 -0800167static unsigned int get_fs_size(char *dev)
168{
169 int fd, block_size;
170 struct ext4_super_block sb;
171 off64_t len;
172
173 if ((fd = open(dev, O_RDONLY)) < 0) {
174 SLOGE("Cannot open device to get filesystem size ");
175 return 0;
176 }
177
178 if (lseek64(fd, 1024, SEEK_SET) < 0) {
179 SLOGE("Cannot seek to superblock");
180 return 0;
181 }
182
183 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
184 SLOGE("Cannot read superblock");
185 return 0;
186 }
187
188 close(fd);
189
190 block_size = 1024 << sb.s_log_block_size;
191 /* compute length in bytes */
192 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
193
194 /* return length in sectors */
195 return (unsigned int) (len / 512);
196}
197
Ken Sumrall160b4d62013-04-22 12:15:39 -0700198static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
199{
200 static int cached_data = 0;
201 static off64_t cached_off = 0;
202 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
203 int fd;
204 char key_loc[PROPERTY_VALUE_MAX];
205 char real_blkdev[PROPERTY_VALUE_MAX];
206 unsigned int nr_sec;
207 int rc = -1;
208
209 if (!cached_data) {
210 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
211
212 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
213 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
214 SLOGE("Cannot open real block device %s\n", real_blkdev);
215 return -1;
216 }
217
218 if ((nr_sec = get_blkdev_size(fd))) {
219 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
220 * encryption info footer and key, and plenty of bytes to spare for future
221 * growth.
222 */
223 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
224 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
225 cached_data = 1;
226 } else {
227 SLOGE("Cannot get size of block device %s\n", real_blkdev);
228 }
229 close(fd);
230 } else {
231 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
232 cached_off = 0;
233 cached_data = 1;
234 }
235 }
236
237 if (cached_data) {
238 if (metadata_fname) {
239 *metadata_fname = cached_metadata_fname;
240 }
241 if (off) {
242 *off = cached_off;
243 }
244 rc = 0;
245 }
246
247 return rc;
248}
249
Ken Sumralle8744072011-01-18 22:01:55 -0800250/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800251 * update the failed mount count but not change the key.
252 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700253static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800254{
255 int fd;
256 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700257 /* starting_off is set to the SEEK_SET offset
258 * where the crypto structure starts
259 */
260 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800261 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700262 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700263 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800264
Ken Sumrall160b4d62013-04-22 12:15:39 -0700265 if (get_crypt_ftr_info(&fname, &starting_off)) {
266 SLOGE("Unable to get crypt_ftr_info\n");
267 return -1;
268 }
269 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700270 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700271 return -1;
272 }
Ken Sumralle550f782013-08-20 13:48:23 -0700273 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
274 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700275 return -1;
276 }
277
278 /* Seek to the start of the crypt footer */
279 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
280 SLOGE("Cannot seek to real block device footer\n");
281 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800282 }
283
284 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
285 SLOGE("Cannot write real block device footer\n");
286 goto errout;
287 }
288
Ken Sumrall3be890f2011-09-14 16:53:46 -0700289 fstat(fd, &statbuf);
290 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700291 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700292 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800293 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800294 goto errout;
295 }
296 }
297
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800298 /* Success! */
299 rc = 0;
300
301errout:
302 close(fd);
303 return rc;
304
305}
306
Ken Sumrall160b4d62013-04-22 12:15:39 -0700307static inline int unix_read(int fd, void* buff, int len)
308{
309 return TEMP_FAILURE_RETRY(read(fd, buff, len));
310}
311
312static inline int unix_write(int fd, const void* buff, int len)
313{
314 return TEMP_FAILURE_RETRY(write(fd, buff, len));
315}
316
317static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
318{
319 memset(pdata, 0, len);
320 pdata->persist_magic = PERSIST_DATA_MAGIC;
321 pdata->persist_valid_entries = 0;
322}
323
324/* A routine to update the passed in crypt_ftr to the lastest version.
325 * fd is open read/write on the device that holds the crypto footer and persistent
326 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
327 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
328 */
329static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
330{
Kenny Root7434b312013-06-14 11:29:53 -0700331 int orig_major = crypt_ftr->major_version;
332 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700333
Kenny Root7434b312013-06-14 11:29:53 -0700334 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
335 struct crypt_persist_data *pdata;
336 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700337
Kenny Rootc4c70f12013-06-14 12:11:38 -0700338 SLOGW("upgrading crypto footer to 1.1");
339
Kenny Root7434b312013-06-14 11:29:53 -0700340 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
341 if (pdata == NULL) {
342 SLOGE("Cannot allocate persisent data\n");
343 return;
344 }
345 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
346
347 /* Need to initialize the persistent data area */
348 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
349 SLOGE("Cannot seek to persisent data offset\n");
350 return;
351 }
352 /* Write all zeros to the first copy, making it invalid */
353 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
354
355 /* Write a valid but empty structure to the second copy */
356 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
357 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
358
359 /* Update the footer */
360 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
361 crypt_ftr->persist_data_offset[0] = pdata_offset;
362 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
363 crypt_ftr->minor_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700364 }
365
Paul Lawrencef4faa572014-01-29 13:31:03 -0800366 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700367 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800368 /* But keep the old kdf_type.
369 * It will get updated later to KDF_SCRYPT after the password has been verified.
370 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700371 crypt_ftr->kdf_type = KDF_PBKDF2;
372 get_device_scrypt_params(crypt_ftr);
373 crypt_ftr->minor_version = 2;
374 }
375
Paul Lawrencef4faa572014-01-29 13:31:03 -0800376 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
377 SLOGW("upgrading crypto footer to 1.3");
378 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
379 crypt_ftr->minor_version = 3;
380 }
381
Kenny Root7434b312013-06-14 11:29:53 -0700382 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
383 if (lseek64(fd, offset, SEEK_SET) == -1) {
384 SLOGE("Cannot seek to crypt footer\n");
385 return;
386 }
387 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700388 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700389}
390
391
392static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800393{
394 int fd;
395 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700396 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800397 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700398 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700399 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800400
Ken Sumrall160b4d62013-04-22 12:15:39 -0700401 if (get_crypt_ftr_info(&fname, &starting_off)) {
402 SLOGE("Unable to get crypt_ftr_info\n");
403 return -1;
404 }
405 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700406 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700407 return -1;
408 }
409 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700410 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700411 return -1;
412 }
413
414 /* Make sure it's 16 Kbytes in length */
415 fstat(fd, &statbuf);
416 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
417 SLOGE("footer file %s is not the expected size!\n", fname);
418 goto errout;
419 }
420
421 /* Seek to the start of the crypt footer */
422 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
423 SLOGE("Cannot seek to real block device footer\n");
424 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800425 }
426
427 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
428 SLOGE("Cannot read real block device footer\n");
429 goto errout;
430 }
431
432 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700433 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800434 goto errout;
435 }
436
Kenny Rootc96a5f82013-06-14 12:08:28 -0700437 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
438 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
439 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800440 goto errout;
441 }
442
Kenny Rootc96a5f82013-06-14 12:08:28 -0700443 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
444 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
445 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800446 }
447
Ken Sumrall160b4d62013-04-22 12:15:39 -0700448 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
449 * copy on disk before returning.
450 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700451 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700452 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800453 }
454
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800455 /* Success! */
456 rc = 0;
457
458errout:
459 close(fd);
460 return rc;
461}
462
Ken Sumrall160b4d62013-04-22 12:15:39 -0700463static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
464{
465 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
466 crypt_ftr->persist_data_offset[1]) {
467 SLOGE("Crypt_ftr persist data regions overlap");
468 return -1;
469 }
470
471 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
472 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
473 return -1;
474 }
475
476 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
477 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
478 CRYPT_FOOTER_OFFSET) {
479 SLOGE("Persistent data extends past crypto footer");
480 return -1;
481 }
482
483 return 0;
484}
485
486static int load_persistent_data(void)
487{
488 struct crypt_mnt_ftr crypt_ftr;
489 struct crypt_persist_data *pdata = NULL;
490 char encrypted_state[PROPERTY_VALUE_MAX];
491 char *fname;
492 int found = 0;
493 int fd;
494 int ret;
495 int i;
496
497 if (persist_data) {
498 /* Nothing to do, we've already loaded or initialized it */
499 return 0;
500 }
501
502
503 /* If not encrypted, just allocate an empty table and initialize it */
504 property_get("ro.crypto.state", encrypted_state, "");
505 if (strcmp(encrypted_state, "encrypted") ) {
506 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
507 if (pdata) {
508 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
509 persist_data = pdata;
510 return 0;
511 }
512 return -1;
513 }
514
515 if(get_crypt_ftr_and_key(&crypt_ftr)) {
516 return -1;
517 }
518
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700519 if ((crypt_ftr.major_version < 1)
520 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700521 SLOGE("Crypt_ftr version doesn't support persistent data");
522 return -1;
523 }
524
525 if (get_crypt_ftr_info(&fname, NULL)) {
526 return -1;
527 }
528
529 ret = validate_persistent_data_storage(&crypt_ftr);
530 if (ret) {
531 return -1;
532 }
533
534 fd = open(fname, O_RDONLY);
535 if (fd < 0) {
536 SLOGE("Cannot open %s metadata file", fname);
537 return -1;
538 }
539
540 if (persist_data == NULL) {
541 pdata = malloc(crypt_ftr.persist_data_size);
542 if (pdata == NULL) {
543 SLOGE("Cannot allocate memory for persistent data");
544 goto err;
545 }
546 }
547
548 for (i = 0; i < 2; i++) {
549 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
550 SLOGE("Cannot seek to read persistent data on %s", fname);
551 goto err2;
552 }
553 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
554 SLOGE("Error reading persistent data on iteration %d", i);
555 goto err2;
556 }
557 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
558 found = 1;
559 break;
560 }
561 }
562
563 if (!found) {
564 SLOGI("Could not find valid persistent data, creating");
565 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
566 }
567
568 /* Success */
569 persist_data = pdata;
570 close(fd);
571 return 0;
572
573err2:
574 free(pdata);
575
576err:
577 close(fd);
578 return -1;
579}
580
581static int save_persistent_data(void)
582{
583 struct crypt_mnt_ftr crypt_ftr;
584 struct crypt_persist_data *pdata;
585 char *fname;
586 off64_t write_offset;
587 off64_t erase_offset;
588 int found = 0;
589 int fd;
590 int ret;
591
592 if (persist_data == NULL) {
593 SLOGE("No persistent data to save");
594 return -1;
595 }
596
597 if(get_crypt_ftr_and_key(&crypt_ftr)) {
598 return -1;
599 }
600
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700601 if ((crypt_ftr.major_version < 1)
602 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700603 SLOGE("Crypt_ftr version doesn't support persistent data");
604 return -1;
605 }
606
607 ret = validate_persistent_data_storage(&crypt_ftr);
608 if (ret) {
609 return -1;
610 }
611
612 if (get_crypt_ftr_info(&fname, NULL)) {
613 return -1;
614 }
615
616 fd = open(fname, O_RDWR);
617 if (fd < 0) {
618 SLOGE("Cannot open %s metadata file", fname);
619 return -1;
620 }
621
622 pdata = malloc(crypt_ftr.persist_data_size);
623 if (pdata == NULL) {
624 SLOGE("Cannot allocate persistant data");
625 goto err;
626 }
627
628 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
629 SLOGE("Cannot seek to read persistent data on %s", fname);
630 goto err2;
631 }
632
633 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
634 SLOGE("Error reading persistent data before save");
635 goto err2;
636 }
637
638 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
639 /* The first copy is the curent valid copy, so write to
640 * the second copy and erase this one */
641 write_offset = crypt_ftr.persist_data_offset[1];
642 erase_offset = crypt_ftr.persist_data_offset[0];
643 } else {
644 /* The second copy must be the valid copy, so write to
645 * the first copy, and erase the second */
646 write_offset = crypt_ftr.persist_data_offset[0];
647 erase_offset = crypt_ftr.persist_data_offset[1];
648 }
649
650 /* Write the new copy first, if successful, then erase the old copy */
651 if (lseek(fd, write_offset, SEEK_SET) < 0) {
652 SLOGE("Cannot seek to write persistent data");
653 goto err2;
654 }
655 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
656 (int) crypt_ftr.persist_data_size) {
657 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
658 SLOGE("Cannot seek to erase previous persistent data");
659 goto err2;
660 }
661 fsync(fd);
662 memset(pdata, 0, crypt_ftr.persist_data_size);
663 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
664 (int) crypt_ftr.persist_data_size) {
665 SLOGE("Cannot write to erase previous persistent data");
666 goto err2;
667 }
668 fsync(fd);
669 } else {
670 SLOGE("Cannot write to save persistent data");
671 goto err2;
672 }
673
674 /* Success */
675 free(pdata);
676 close(fd);
677 return 0;
678
679err2:
680 free(pdata);
681err:
682 close(fd);
683 return -1;
684}
685
Paul Lawrencef4faa572014-01-29 13:31:03 -0800686static int hexdigit (char c)
687{
688 if (c >= '0' && c <= '9') return c - '0';
689 c = tolower(c);
690 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
691 return -1;
692}
693
694static unsigned char* convert_hex_ascii_to_key(const char* master_key_ascii,
695 unsigned int* out_keysize)
696{
697 unsigned int i;
698 *out_keysize = 0;
699
700 size_t size = strlen (master_key_ascii);
701 if (size % 2) {
702 SLOGE("Trying to convert ascii string of odd length");
703 return NULL;
704 }
705
706 unsigned char* master_key = (unsigned char*) malloc(size / 2);
707 if (master_key == 0) {
708 SLOGE("Cannot allocate");
709 return NULL;
710 }
711
712 for (i = 0; i < size; i += 2) {
713 int high_nibble = hexdigit (master_key_ascii[i]);
714 int low_nibble = hexdigit (master_key_ascii[i + 1]);
715
716 if(high_nibble < 0 || low_nibble < 0) {
717 SLOGE("Invalid hex string");
718 free (master_key);
719 return NULL;
720 }
721
722 master_key[*out_keysize] = high_nibble * 16 + low_nibble;
723 (*out_keysize)++;
724 }
725
726 return master_key;
727}
728
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800729/* Convert a binary key of specified length into an ascii hex string equivalent,
730 * without the leading 0x and with null termination
731 */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800732static void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800733 char *master_key_ascii)
734{
735 unsigned int i, a;
736 unsigned char nibble;
737
738 for (i=0, a=0; i<keysize; i++, a+=2) {
739 /* For each byte, write out two ascii hex digits */
740 nibble = (master_key[i] >> 4) & 0xf;
741 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
742
743 nibble = master_key[i] & 0xf;
744 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
745 }
746
747 /* Add the null termination */
748 master_key_ascii[a] = '\0';
749
750}
751
Ken Sumralldb5e0262013-02-05 17:39:48 -0800752static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
753 char *real_blk_name, const char *name, int fd,
754 char *extra_params)
755{
756 char buffer[DM_CRYPT_BUF_SIZE];
757 struct dm_ioctl *io;
758 struct dm_target_spec *tgt;
759 char *crypt_params;
760 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
761 int i;
762
763 io = (struct dm_ioctl *) buffer;
764
765 /* Load the mapping table for this device */
766 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
767
768 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
769 io->target_count = 1;
770 tgt->status = 0;
771 tgt->sector_start = 0;
772 tgt->length = crypt_ftr->fs_size;
773 strcpy(tgt->target_type, "crypt");
774
775 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
776 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
777 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
778 master_key_ascii, real_blk_name, extra_params);
779 crypt_params += strlen(crypt_params) + 1;
780 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
781 tgt->next = crypt_params - buffer;
782
783 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
784 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
785 break;
786 }
787 usleep(500000);
788 }
789
790 if (i == TABLE_LOAD_RETRIES) {
791 /* We failed to load the table, return an error */
792 return -1;
793 } else {
794 return i + 1;
795 }
796}
797
798
799static int get_dm_crypt_version(int fd, const char *name, int *version)
800{
801 char buffer[DM_CRYPT_BUF_SIZE];
802 struct dm_ioctl *io;
803 struct dm_target_versions *v;
804 int i;
805
806 io = (struct dm_ioctl *) buffer;
807
808 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
809
810 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
811 return -1;
812 }
813
814 /* Iterate over the returned versions, looking for name of "crypt".
815 * When found, get and return the version.
816 */
817 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
818 while (v->next) {
819 if (! strcmp(v->name, "crypt")) {
820 /* We found the crypt driver, return the version, and get out */
821 version[0] = v->version[0];
822 version[1] = v->version[1];
823 version[2] = v->version[2];
824 return 0;
825 }
826 v = (struct dm_target_versions *)(((char *)v) + v->next);
827 }
828
829 return -1;
830}
831
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800832static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -0700833 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800834{
835 char buffer[DM_CRYPT_BUF_SIZE];
836 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
837 char *crypt_params;
838 struct dm_ioctl *io;
839 struct dm_target_spec *tgt;
840 unsigned int minor;
841 int fd;
Ken Sumralle919efe2012-09-29 17:07:41 -0700842 int i;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800843 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800844 int version[3];
845 char *extra_params;
846 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800847
848 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
849 SLOGE("Cannot open device-mapper\n");
850 goto errout;
851 }
852
853 io = (struct dm_ioctl *) buffer;
854
855 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
856 if (ioctl(fd, DM_DEV_CREATE, io)) {
857 SLOGE("Cannot create dm-crypt device\n");
858 goto errout;
859 }
860
861 /* Get the device status, in particular, the name of it's device file */
862 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
863 if (ioctl(fd, DM_DEV_STATUS, io)) {
864 SLOGE("Cannot retrieve dm-crypt device status\n");
865 goto errout;
866 }
867 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
868 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
869
Ken Sumralldb5e0262013-02-05 17:39:48 -0800870 extra_params = "";
871 if (! get_dm_crypt_version(fd, name, version)) {
872 /* Support for allow_discards was added in version 1.11.0 */
873 if ((version[0] >= 2) ||
874 ((version[0] == 1) && (version[1] >= 11))) {
875 extra_params = "1 allow_discards";
876 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
877 }
Ken Sumralle919efe2012-09-29 17:07:41 -0700878 }
879
Ken Sumralldb5e0262013-02-05 17:39:48 -0800880 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
881 fd, extra_params);
882 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800883 SLOGE("Cannot load dm-crypt mapping table.\n");
884 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800885 } else if (load_count > 1) {
886 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800887 }
888
889 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -0800890 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800891
892 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
893 SLOGE("Cannot resume the dm-crypt device\n");
894 goto errout;
895 }
896
897 /* We made it here with no errors. Woot! */
898 retval = 0;
899
900errout:
901 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
902
903 return retval;
904}
905
Ken Sumrall29d8da82011-05-18 17:20:07 -0700906static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800907{
908 int fd;
909 char buffer[DM_CRYPT_BUF_SIZE];
910 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800911 int retval = -1;
912
913 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
914 SLOGE("Cannot open device-mapper\n");
915 goto errout;
916 }
917
918 io = (struct dm_ioctl *) buffer;
919
920 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
921 if (ioctl(fd, DM_DEV_REMOVE, io)) {
922 SLOGE("Cannot remove dm-crypt device\n");
923 goto errout;
924 }
925
926 /* We made it here with no errors. Woot! */
927 retval = 0;
928
929errout:
930 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
931
932 return retval;
933
934}
935
Paul Lawrence13486032014-02-03 13:28:11 -0800936static int pbkdf2(const char *passwd, unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -0800937 unsigned char *ikey, void *params UNUSED)
938{
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800939 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800940 unsigned int keysize;
941 char* master_key = (char*)convert_hex_ascii_to_key(passwd, &keysize);
942 if (!master_key) return -1;
943 PKCS5_PBKDF2_HMAC_SHA1(master_key, keysize, salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800944 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Paul Lawrencef4faa572014-01-29 13:31:03 -0800945
946 free (master_key);
947 return 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800948}
949
Paul Lawrence13486032014-02-03 13:28:11 -0800950static int scrypt(const char *passwd, unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -0800951 unsigned char *ikey, void *params)
952{
Kenny Rootc4c70f12013-06-14 12:11:38 -0700953 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
954
955 int N = 1 << ftr->N_factor;
956 int r = 1 << ftr->r_factor;
957 int p = 1 << ftr->p_factor;
958
959 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800960 unsigned int keysize;
961 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &keysize);
962 if (!master_key) return -1;
963 crypto_scrypt(master_key, keysize, salt, SALT_LEN, N, r, p, ikey,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700964 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -0800965
966 free (master_key);
967 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700968}
969
Paul Lawrence13486032014-02-03 13:28:11 -0800970static int encrypt_master_key(const char *passwd, unsigned char *salt,
Ken Sumralle8744072011-01-18 22:01:55 -0800971 unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700972 unsigned char *encrypted_master_key,
973 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800974{
975 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
976 EVP_CIPHER_CTX e_ctx;
977 int encrypted_len, final_len;
978
979 /* Turn the password into a key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700980 get_device_scrypt_params(crypt_ftr);
Paul Lawrencef4faa572014-01-29 13:31:03 -0800981 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
982 SLOGE("scrypt failed");
983 return -1;
984 }
Kenny Rootc4c70f12013-06-14 12:11:38 -0700985
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800986 /* Initialize the decryption engine */
987 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
988 SLOGE("EVP_EncryptInit failed\n");
989 return -1;
990 }
991 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800992
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800993 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800994 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
995 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800996 SLOGE("EVP_EncryptUpdate failed\n");
997 return -1;
998 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800999 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001000 SLOGE("EVP_EncryptFinal failed\n");
1001 return -1;
1002 }
1003
1004 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1005 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1006 return -1;
1007 } else {
1008 return 0;
1009 }
1010}
1011
JP Abgrall7bdfa522013-11-15 13:42:56 -08001012static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
Ken Sumralle8744072011-01-18 22:01:55 -08001013 unsigned char *encrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001014 unsigned char *decrypted_master_key,
1015 kdf_func kdf, void *kdf_params)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001016{
1017 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 -08001018 EVP_CIPHER_CTX d_ctx;
1019 int decrypted_len, final_len;
1020
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001021 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001022 if (kdf(passwd, salt, ikey, kdf_params)) {
1023 SLOGE("kdf failed");
1024 return -1;
1025 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001026
1027 /* Initialize the decryption engine */
1028 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1029 return -1;
1030 }
1031 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1032 /* Decrypt the master key */
1033 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1034 encrypted_master_key, KEY_LEN_BYTES)) {
1035 return -1;
1036 }
1037 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1038 return -1;
1039 }
1040
1041 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1042 return -1;
1043 } else {
1044 return 0;
1045 }
1046}
1047
Kenny Rootc4c70f12013-06-14 12:11:38 -07001048static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001049{
Kenny Rootc4c70f12013-06-14 12:11:38 -07001050 if (ftr->kdf_type == KDF_SCRYPT) {
1051 *kdf = scrypt;
1052 *kdf_params = ftr;
1053 } else {
1054 *kdf = pbkdf2;
1055 *kdf_params = NULL;
1056 }
1057}
1058
JP Abgrall7bdfa522013-11-15 13:42:56 -08001059static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001060 struct crypt_mnt_ftr *crypt_ftr)
1061{
1062 kdf_func kdf;
1063 void *kdf_params;
1064 int ret;
1065
1066 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001067 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, decrypted_master_key, kdf,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001068 kdf_params);
1069 if (ret != 0) {
1070 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001071 }
1072
1073 return ret;
1074}
1075
1076static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1077 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001078 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001079 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001080 EVP_CIPHER_CTX e_ctx;
1081 int encrypted_len, final_len;
1082
1083 /* Get some random bits for a key */
1084 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001085 read(fd, key_buf, sizeof(key_buf));
1086 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001087 close(fd);
1088
1089 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001090 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001091}
1092
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001093static int wait_and_unmount(char *mountpoint)
1094{
1095 int i, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001096#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001097
1098 /* Now umount the tmpfs filesystem */
1099 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
1100 if (umount(mountpoint)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001101 if (errno == EINVAL) {
1102 /* EINVAL is returned if the directory is not a mountpoint,
1103 * i.e. there is no filesystem mounted there. So just get out.
1104 */
1105 break;
1106 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001107 sleep(1);
1108 i++;
1109 } else {
1110 break;
1111 }
1112 }
1113
1114 if (i < WAIT_UNMOUNT_COUNT) {
1115 SLOGD("unmounting %s succeeded\n", mountpoint);
1116 rc = 0;
1117 } else {
1118 SLOGE("unmounting %s failed\n", mountpoint);
1119 rc = -1;
1120 }
1121
1122 return rc;
1123}
1124
Ken Sumrallc5872692013-05-14 15:26:31 -07001125#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001126static int prep_data_fs(void)
1127{
1128 int i;
1129
1130 /* Do the prep of the /data filesystem */
1131 property_set("vold.post_fs_data_done", "0");
1132 property_set("vold.decrypt", "trigger_post_fs_data");
1133 SLOGD("Just triggered post_fs_data\n");
1134
Ken Sumrallc5872692013-05-14 15:26:31 -07001135 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001136 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001137 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001138
1139 property_get("vold.post_fs_data_done", p, "0");
1140 if (*p == '1') {
1141 break;
1142 } else {
1143 usleep(250000);
1144 }
1145 }
1146 if (i == DATA_PREP_TIMEOUT) {
1147 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001148 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001149 return -1;
1150 } else {
1151 SLOGD("post_fs_data done\n");
1152 return 0;
1153 }
1154}
1155
Paul Lawrencef4faa572014-01-29 13:31:03 -08001156static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001157{
1158 char fs_type[32];
1159 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001160 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001161 char fs_options[256];
1162 unsigned long mnt_flags;
1163 struct stat statbuf;
1164 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001165 static int restart_successful = 0;
1166
1167 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001168 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001169 SLOGE("Encrypted filesystem not validated, aborting");
1170 return -1;
1171 }
1172
1173 if (restart_successful) {
1174 SLOGE("System already restarted with encrypted disk, aborting");
1175 return -1;
1176 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001177
Paul Lawrencef4faa572014-01-29 13:31:03 -08001178 if (restart_main) {
1179 /* Here is where we shut down the framework. The init scripts
1180 * start all services in one of three classes: core, main or late_start.
1181 * On boot, we start core and main. Now, we stop main, but not core,
1182 * as core includes vold and a few other really important things that
1183 * we need to keep running. Once main has stopped, we should be able
1184 * to umount the tmpfs /data, then mount the encrypted /data.
1185 * We then restart the class main, and also the class late_start.
1186 * At the moment, I've only put a few things in late_start that I know
1187 * are not needed to bring up the framework, and that also cause problems
1188 * with unmounting the tmpfs /data, but I hope to add add more services
1189 * to the late_start class as we optimize this to decrease the delay
1190 * till the user is asked for the password to the filesystem.
1191 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001192
Paul Lawrencef4faa572014-01-29 13:31:03 -08001193 /* The init files are setup to stop the class main when vold.decrypt is
1194 * set to trigger_reset_main.
1195 */
1196 property_set("vold.decrypt", "trigger_reset_main");
1197 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001198
Paul Lawrencef4faa572014-01-29 13:31:03 -08001199 /* Ugh, shutting down the framework is not synchronous, so until it
1200 * can be fixed, this horrible hack will wait a moment for it all to
1201 * shut down before proceeding. Without it, some devices cannot
1202 * restart the graphics services.
1203 */
1204 sleep(2);
1205 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001206
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001207 /* Now that the framework is shutdown, we should be able to umount()
1208 * the tmpfs filesystem, and mount the real one.
1209 */
1210
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001211 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1212 if (strlen(crypto_blkdev) == 0) {
1213 SLOGE("fs_crypto_blkdev not set\n");
1214 return -1;
1215 }
1216
Ken Sumralle5032c42012-04-01 23:58:44 -07001217 if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001218 /* If ro.crypto.readonly is set to 1, mount the decrypted
1219 * filesystem readonly. This is used when /data is mounted by
1220 * recovery mode.
1221 */
1222 char ro_prop[PROPERTY_VALUE_MAX];
1223 property_get("ro.crypto.readonly", ro_prop, "");
1224 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1225 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1226 rec->flags |= MS_RDONLY;
1227 }
1228
Ken Sumralle5032c42012-04-01 23:58:44 -07001229 /* If that succeeded, then mount the decrypted filesystem */
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001230 fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001231
Ken Sumralle5032c42012-04-01 23:58:44 -07001232 property_set("vold.decrypt", "trigger_load_persist_props");
1233 /* Create necessary paths on /data */
1234 if (prep_data_fs()) {
1235 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001236 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001237
1238 /* startup service classes main and late_start */
1239 property_set("vold.decrypt", "trigger_restart_framework");
1240 SLOGD("Just triggered restart_framework\n");
1241
1242 /* Give it a few moments to get started */
1243 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001244 }
1245
Ken Sumrall0cc16632011-01-18 20:32:26 -08001246 if (rc == 0) {
1247 restart_successful = 1;
1248 }
1249
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001250 return rc;
1251}
1252
Paul Lawrencef4faa572014-01-29 13:31:03 -08001253int cryptfs_restart(void)
1254{
1255 /* Call internal implementation forcing a restart of main service group */
1256 return cryptfs_restart_internal(1);
1257}
1258
Mark Salyzyn3e971272014-01-21 13:27:04 -08001259static int do_crypto_complete(char *mount_point UNUSED)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001260{
1261 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001262 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001263 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001264
1265 property_get("ro.crypto.state", encrypted_state, "");
1266 if (strcmp(encrypted_state, "encrypted") ) {
1267 SLOGE("not running with encryption, aborting");
1268 return 1;
1269 }
1270
Ken Sumrall160b4d62013-04-22 12:15:39 -07001271 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001272 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001273
Ken Sumralle1a45852011-12-14 21:24:27 -08001274 /*
1275 * Only report this error if key_loc is a file and it exists.
1276 * If the device was never encrypted, and /data is not mountable for
1277 * some reason, returning 1 should prevent the UI from presenting the
1278 * a "enter password" screen, or worse, a "press button to wipe the
1279 * device" screen.
1280 */
1281 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1282 SLOGE("master key file does not exist, aborting");
1283 return 1;
1284 } else {
1285 SLOGE("Error getting crypt footer and key\n");
1286 return -1;
1287 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001288 }
1289
1290 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1291 SLOGE("Encryption process didn't finish successfully\n");
1292 return -2; /* -2 is the clue to the UI that there is no usable data on the disk,
1293 * and give the user an option to wipe the disk */
1294 }
1295
1296 /* We passed the test! We shall diminish, and return to the west */
1297 return 0;
1298}
1299
Paul Lawrencef4faa572014-01-29 13:31:03 -08001300static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1301 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001302{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001303 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001304 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001305 char crypto_blkdev[MAXPATHLEN];
1306 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001307 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001308 unsigned int orig_failed_decrypt_count;
1309 int rc;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001310 kdf_func kdf;
1311 void *kdf_params;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001312
Paul Lawrencef4faa572014-01-29 13:31:03 -08001313 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1314 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001315
Paul Lawrencef4faa572014-01-29 13:31:03 -08001316 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
1317 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001318 SLOGE("Failed to decrypt master key\n");
1319 return -1;
1320 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001321 }
1322
Paul Lawrencef4faa572014-01-29 13:31:03 -08001323 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1324
1325 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1326 real_blkdev, crypto_blkdev, label)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001327 SLOGE("Error creating decrypted block device\n");
1328 return -1;
1329 }
1330
Alex Klyubin707795a2013-05-10 15:17:07 -07001331 /* If init detects an encrypted filesystem, it writes a file for each such
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001332 * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
1333 * files and passes that data to me */
1334 /* Create a tmp mount point to try mounting the decryptd fs
1335 * Since we're here, the mount_point should be a tmpfs filesystem, so make
1336 * a directory in it to test mount the decrypted filesystem.
1337 */
1338 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1339 mkdir(tmp_mount_point, 0755);
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001340 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001341 SLOGE("Error temp mounting decrypted block device\n");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001342 delete_crypto_blk_dev(label);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001343 crypt_ftr->failed_decrypt_count++;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001344 } else {
1345 /* Success, so just umount and we'll mount it properly when we restart
1346 * the framework.
1347 */
1348 umount(tmp_mount_point);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001349 crypt_ftr->failed_decrypt_count = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001350 }
1351
Paul Lawrencef4faa572014-01-29 13:31:03 -08001352 if (orig_failed_decrypt_count != crypt_ftr->failed_decrypt_count) {
1353 put_crypt_ftr_and_key(crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001354 }
1355
Paul Lawrencef4faa572014-01-29 13:31:03 -08001356 if (crypt_ftr->failed_decrypt_count) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001357 /* We failed to mount the device, so return an error */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001358 rc = crypt_ftr->failed_decrypt_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001359
1360 } else {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001361 /* Woot! Success! Save the name of the crypto block device
1362 * so we can mount it when restarting the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001363 */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001364 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001365
1366 /* Also save a the master key so we can reencrypted the key
1367 * the key when we want to change the password on it.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001368 */
Jason parks70a4b3f2011-01-28 10:10:47 -06001369 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001370 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001371 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001372 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001373 rc = 0;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001374 /*
1375 * Upgrade if we're not using the latest KDF.
1376 */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001377 if (crypt_ftr->kdf_type != KDF_SCRYPT) {
1378 crypt_ftr->kdf_type = KDF_SCRYPT;
1379 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1380 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001381 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001382 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001383 }
1384 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1385 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001386 }
1387
1388 return rc;
1389}
1390
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001391/* Called by vold when it wants to undo the crypto mapping of a volume it
1392 * manages. This is usually in response to a factory reset, when we want
1393 * to undo the crypto mapping so the volume is formatted in the clear.
1394 */
1395int cryptfs_revert_volume(const char *label)
1396{
1397 return delete_crypto_blk_dev((char *)label);
1398}
1399
Ken Sumrall29d8da82011-05-18 17:20:07 -07001400/*
1401 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1402 * Setup a dm-crypt mapping, use the saved master key from
1403 * setting up the /data mapping, and return the new device path.
1404 */
1405int cryptfs_setup_volume(const char *label, int major, int minor,
1406 char *crypto_sys_path, unsigned int max_path,
1407 int *new_major, int *new_minor)
1408{
1409 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1410 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001411 struct stat statbuf;
1412 int nr_sec, fd;
1413
1414 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1415
Ken Sumrall160b4d62013-04-22 12:15:39 -07001416 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001417
1418 /* Update the fs_size field to be the size of the volume */
1419 fd = open(real_blkdev, O_RDONLY);
1420 nr_sec = get_blkdev_size(fd);
1421 close(fd);
1422 if (nr_sec == 0) {
1423 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1424 return -1;
1425 }
1426
1427 sd_crypt_ftr.fs_size = nr_sec;
1428 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1429 crypto_blkdev, label);
1430
1431 stat(crypto_blkdev, &statbuf);
1432 *new_major = MAJOR(statbuf.st_rdev);
1433 *new_minor = MINOR(statbuf.st_rdev);
1434
1435 /* Create path to sys entry for this block device */
1436 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1437
1438 return 0;
1439}
1440
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001441int cryptfs_crypto_complete(void)
1442{
1443 return do_crypto_complete("/data");
1444}
1445
Paul Lawrencef4faa572014-01-29 13:31:03 -08001446int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1447{
1448 char encrypted_state[PROPERTY_VALUE_MAX];
1449 property_get("ro.crypto.state", encrypted_state, "");
1450 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1451 SLOGE("encrypted fs already validated or not running with encryption,"
1452 " aborting");
1453 return -1;
1454 }
1455
1456 if (get_crypt_ftr_and_key(crypt_ftr)) {
1457 SLOGE("Error getting crypt footer and key");
1458 return -1;
1459 }
1460
1461 return 0;
1462}
1463
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001464int cryptfs_check_passwd(char *passwd)
1465{
Paul Lawrencef4faa572014-01-29 13:31:03 -08001466 struct crypt_mnt_ftr crypt_ftr;
1467 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001468
Paul Lawrencef4faa572014-01-29 13:31:03 -08001469 rc = check_unmounted_and_get_ftr(&crypt_ftr);
1470 if (rc)
1471 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001472
Paul Lawrencef4faa572014-01-29 13:31:03 -08001473 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
1474 DATA_MNT_POINT, "userdata");
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001475
1476 if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
1477 just_decrypted = 1;
1478 }
1479
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001480 return rc;
1481}
1482
Ken Sumrall3ad90722011-10-04 20:38:29 -07001483int cryptfs_verify_passwd(char *passwd)
1484{
1485 struct crypt_mnt_ftr crypt_ftr;
1486 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001487 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001488 char encrypted_state[PROPERTY_VALUE_MAX];
1489 int rc;
1490
1491 property_get("ro.crypto.state", encrypted_state, "");
1492 if (strcmp(encrypted_state, "encrypted") ) {
1493 SLOGE("device not encrypted, aborting");
1494 return -2;
1495 }
1496
1497 if (!master_key_saved) {
1498 SLOGE("encrypted fs not yet mounted, aborting");
1499 return -1;
1500 }
1501
1502 if (!saved_mount_point) {
1503 SLOGE("encrypted fs failed to save mount point, aborting");
1504 return -1;
1505 }
1506
Ken Sumrall160b4d62013-04-22 12:15:39 -07001507 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001508 SLOGE("Error getting crypt footer and key\n");
1509 return -1;
1510 }
1511
1512 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1513 /* If the device has no password, then just say the password is valid */
1514 rc = 0;
1515 } else {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001516 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001517 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1518 /* They match, the password is correct */
1519 rc = 0;
1520 } else {
1521 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1522 sleep(1);
1523 rc = 1;
1524 }
1525 }
1526
1527 return rc;
1528}
1529
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001530/* Initialize a crypt_mnt_ftr structure. The keysize is
1531 * defaulted to 16 bytes, and the filesystem size to 0.
1532 * Presumably, at a minimum, the caller will update the
1533 * filesystem size and crypto_type_name after calling this function.
1534 */
1535static void cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
1536{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001537 off64_t off;
1538
1539 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001540 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001541 ftr->major_version = CURRENT_MAJOR_VERSION;
1542 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001543 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001544 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001545
Kenny Rootc4c70f12013-06-14 12:11:38 -07001546 ftr->kdf_type = KDF_SCRYPT;
1547 get_device_scrypt_params(ftr);
1548
Ken Sumrall160b4d62013-04-22 12:15:39 -07001549 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1550 if (get_crypt_ftr_info(NULL, &off) == 0) {
1551 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1552 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1553 ftr->persist_data_size;
1554 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001555}
1556
Ken Sumrall29d8da82011-05-18 17:20:07 -07001557static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001558{
Ken Sumralle550f782013-08-20 13:48:23 -07001559 const char *args[10];
1560 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1561 int num_args;
1562 int status;
1563 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001564 int rc = -1;
1565
Ken Sumrall29d8da82011-05-18 17:20:07 -07001566 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001567 args[0] = "/system/bin/make_ext4fs";
1568 args[1] = "-a";
1569 args[2] = "/data";
1570 args[3] = "-l";
1571 snprintf(size_str, sizeof(size_str), "%lld", size * 512);
1572 args[4] = size_str;
1573 args[5] = crypto_blkdev;
1574 num_args = 6;
1575 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1576 args[0], args[1], args[2], args[3], args[4], args[5]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001577 } else if (type== FAT_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001578 args[0] = "/system/bin/newfs_msdos";
1579 args[1] = "-F";
1580 args[2] = "32";
1581 args[3] = "-O";
1582 args[4] = "android";
1583 args[5] = "-c";
1584 args[6] = "8";
1585 args[7] = "-s";
1586 snprintf(size_str, sizeof(size_str), "%lld", size);
1587 args[8] = size_str;
1588 args[9] = crypto_blkdev;
1589 num_args = 10;
1590 SLOGI("Making empty filesystem with command %s %s %s %s %s %s %s %s %s %s\n",
1591 args[0], args[1], args[2], args[3], args[4], args[5],
1592 args[6], args[7], args[8], args[9]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001593 } else {
1594 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1595 return -1;
1596 }
1597
Ken Sumralle550f782013-08-20 13:48:23 -07001598 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1599
1600 if (tmp != 0) {
1601 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001602 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07001603 if (WIFEXITED(status)) {
1604 if (WEXITSTATUS(status)) {
1605 SLOGE("Error creating filesystem on %s, exit status %d ",
1606 crypto_blkdev, WEXITSTATUS(status));
1607 } else {
1608 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
1609 rc = 0;
1610 }
1611 } else {
1612 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
1613 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001614 }
1615
1616 return rc;
1617}
1618
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001619#define CRYPT_INPLACE_BUFSIZE 4096
1620#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / 512)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001621
1622/* aligned 32K writes tends to make flash happy.
1623 * SD card association recommends it.
1624 */
1625#define BLOCKS_AT_A_TIME 8
1626
1627struct encryptGroupsData
1628{
1629 int realfd;
1630 int cryptofd;
1631 off64_t numblocks;
1632 off64_t one_pct, cur_pct, new_pct;
1633 off64_t blocks_already_done, tot_numblocks;
1634 char* real_blkdev, * crypto_blkdev;
1635 int count;
1636 off64_t offset;
1637 char* buffer;
1638};
1639
1640static void update_progress(struct encryptGroupsData* data)
1641{
1642 data->blocks_already_done++;
1643 data->new_pct = data->blocks_already_done / data->one_pct;
1644 if (data->new_pct > data->cur_pct) {
1645 char buf[8];
1646 data->cur_pct = data->new_pct;
1647 snprintf(buf, sizeof(buf), "%lld", data->cur_pct);
1648 property_set("vold.encrypt_progress", buf);
1649 }
1650}
1651
1652static int flush_outstanding_data(struct encryptGroupsData* data)
1653{
1654 if (data->count == 0) {
1655 return 0;
1656 }
1657
1658 SLOGV("Copying %d blocks at offset %llx", data->count, data->offset);
1659
1660 if (pread64(data->realfd, data->buffer,
1661 info.block_size * data->count, data->offset)
1662 <= 0) {
1663 SLOGE("Error reading real_blkdev %s for inplace encrypt",
1664 data->real_blkdev);
1665 return -1;
1666 }
1667
1668 if (pwrite64(data->cryptofd, data->buffer,
1669 info.block_size * data->count, data->offset)
1670 <= 0) {
1671 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
1672 data->crypto_blkdev);
1673 return -1;
1674 }
1675
1676 data->count = 0;
1677 return 0;
1678}
1679
1680static int encrypt_groups(struct encryptGroupsData* data)
1681{
1682 unsigned int i;
1683 u8 *block_bitmap = 0;
1684 unsigned int block;
1685 off64_t ret;
1686 int rc = -1;
1687
1688 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
1689 if (!data->buffer) {
1690 SLOGE("Failed to allocate crypto buffer");
1691 goto errout;
1692 }
1693
1694 block_bitmap = malloc(info.block_size);
1695 if (!block_bitmap) {
1696 SLOGE("failed to allocate block bitmap");
1697 goto errout;
1698 }
1699
1700 for (i = 0; i < aux_info.groups; ++i) {
1701 SLOGI("Encrypting group %d", i);
1702
1703 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
1704 u32 block_count = min(info.blocks_per_group,
1705 aux_info.len_blocks - first_block);
1706
1707 off64_t offset = (u64)info.block_size
1708 * aux_info.bg_desc[i].bg_block_bitmap;
1709
1710 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
1711 if (ret != (int)info.block_size) {
1712 SLOGE("failed to read all of block group bitmap %d", i);
1713 goto errout;
1714 }
1715
1716 offset = (u64)info.block_size * first_block;
1717
1718 data->count = 0;
1719
1720 for (block = 0; block < block_count; block++) {
1721 update_progress(data);
1722 if (bitmap_get_bit(block_bitmap, block)) {
1723 if (data->count == 0) {
1724 data->offset = offset;
1725 }
1726 data->count++;
1727 } else {
1728 if (flush_outstanding_data(data)) {
1729 goto errout;
1730 }
1731 }
1732
1733 offset += info.block_size;
1734
1735 /* Write data if we are aligned or buffer size reached */
1736 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
1737 || data->count == BLOCKS_AT_A_TIME) {
1738 if (flush_outstanding_data(data)) {
1739 goto errout;
1740 }
1741 }
1742 }
1743 if (flush_outstanding_data(data)) {
1744 goto errout;
1745 }
1746 }
1747
1748 rc = 0;
1749
1750errout:
1751 free(data->buffer);
1752 free(block_bitmap);
1753 return rc;
1754}
1755
1756static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
1757 char *real_blkdev,
1758 off64_t size,
1759 off64_t *size_already_done,
1760 off64_t tot_size)
1761{
1762 int i;
1763 struct encryptGroupsData data;
1764 int rc = -1;
1765
1766 memset(&data, 0, sizeof(data));
1767 data.real_blkdev = real_blkdev;
1768 data.crypto_blkdev = crypto_blkdev;
1769
1770 if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
1771 SLOGE("Error opening real_blkdev %s for inplace encrypt\n",
1772 real_blkdev);
1773 goto errout;
1774 }
1775
1776 if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
1777 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n",
1778 crypto_blkdev);
1779 goto errout;
1780 }
1781
1782 if (setjmp(setjmp_env)) {
1783 SLOGE("Reading extent caused an exception");
1784 goto errout;
1785 }
1786
1787 if (read_ext(data.realfd, 0) != 0) {
1788 SLOGE("Failed to read extent");
1789 goto errout;
1790 }
1791
1792 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
1793 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
1794 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
1795
1796 SLOGI("Encrypting filesystem in place...");
1797
1798 data.one_pct = data.tot_numblocks / 100;
1799 data.cur_pct = 0;
1800
1801 rc = encrypt_groups(&data);
1802 if (rc) {
1803 SLOGE("Error encrypting groups");
1804 goto errout;
1805 }
1806
1807 *size_already_done += size;
1808 rc = 0;
1809
1810errout:
1811 close(data.realfd);
1812 close(data.cryptofd);
1813
1814 return rc;
1815}
1816
1817static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
1818 off64_t size, off64_t *size_already_done,
1819 off64_t tot_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001820{
1821 int realfd, cryptofd;
1822 char *buf[CRYPT_INPLACE_BUFSIZE];
1823 int rc = -1;
1824 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001825 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001826 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001827
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001828 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
1829 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
1830 return -1;
1831 }
1832
1833 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
1834 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1835 close(realfd);
1836 return -1;
1837 }
1838
1839 /* This is pretty much a simple loop of reading 4K, and writing 4K.
1840 * The size passed in is the number of 512 byte sectors in the filesystem.
1841 * So compute the number of whole 4K blocks we should read/write,
1842 * and the remainder.
1843 */
1844 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
1845 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001846 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
1847 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001848
1849 SLOGE("Encrypting filesystem in place...");
1850
Ken Sumrall29d8da82011-05-18 17:20:07 -07001851 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001852 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001853 /* process the majority of the filesystem in blocks */
1854 for (i=0; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001855 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001856 if (new_pct > cur_pct) {
1857 char buf[8];
1858
1859 cur_pct = new_pct;
1860 snprintf(buf, sizeof(buf), "%lld", cur_pct);
1861 property_set("vold.encrypt_progress", buf);
1862 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001863 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1864 SLOGE("Error reading real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1865 goto errout;
1866 }
1867 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1868 SLOGE("Error writing crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1869 goto errout;
1870 }
1871 }
1872
1873 /* Do any remaining sectors */
1874 for (i=0; i<remainder; i++) {
1875 if (unix_read(realfd, buf, 512) <= 0) {
1876 SLOGE("Error reading rival sectors from real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1877 goto errout;
1878 }
1879 if (unix_write(cryptofd, buf, 512) <= 0) {
1880 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1881 goto errout;
1882 }
1883 }
1884
Ken Sumrall29d8da82011-05-18 17:20:07 -07001885 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001886 rc = 0;
1887
1888errout:
1889 close(realfd);
1890 close(cryptofd);
1891
1892 return rc;
1893}
1894
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001895static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
1896 off64_t size, off64_t *size_already_done,
1897 off64_t tot_size)
1898{
1899 if (cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
1900 size, size_already_done, tot_size) == 0) {
1901 return 0;
1902 }
1903
1904 return cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
1905 size, size_already_done, tot_size);
1906}
1907
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001908#define CRYPTO_ENABLE_WIPE 1
1909#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001910
1911#define FRAMEWORK_BOOT_WAIT 60
1912
Ken Sumrall29d8da82011-05-18 17:20:07 -07001913static inline int should_encrypt(struct volume_info *volume)
1914{
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001915 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
Ken Sumrall29d8da82011-05-18 17:20:07 -07001916 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
1917}
1918
Paul Lawrence13486032014-02-03 13:28:11 -08001919int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
1920 int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001921{
1922 int how = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001923 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN], sd_crypto_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07001924 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001925 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07001926 int rc=-1, fd, i, ret;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001927 struct crypt_mnt_ftr crypt_ftr, sd_crypt_ftr;;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001928 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001929 char tmpfs_options[PROPERTY_VALUE_MAX];
1930 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001931 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07001932 char key_loc[PROPERTY_VALUE_MAX];
1933 char fuse_sdcard[PROPERTY_VALUE_MAX];
1934 char *sd_mnt_point;
1935 char sd_blk_dev[256] = { 0 };
1936 int num_vols;
1937 struct volume_info *vol_list = 0;
1938 off64_t cur_encryption_done=0, tot_encryption_size=0;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001939
1940 property_get("ro.crypto.state", encrypted_state, "");
JP Abgrall502dc742013-11-01 13:06:20 -07001941 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001942 SLOGE("Device is already running encrypted, aborting");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001943 goto error_unencrypted;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001944 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001945
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001946 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001947
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001948 if (!strcmp(howarg, "wipe")) {
1949 how = CRYPTO_ENABLE_WIPE;
1950 } else if (! strcmp(howarg, "inplace")) {
1951 how = CRYPTO_ENABLE_INPLACE;
1952 } else {
1953 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08001954 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001955 }
1956
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001957 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001958
Ken Sumrall3ed82362011-01-28 23:31:16 -08001959 /* Get the size of the real block device */
1960 fd = open(real_blkdev, O_RDONLY);
1961 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
1962 SLOGE("Cannot get size of block device %s\n", real_blkdev);
1963 goto error_unencrypted;
1964 }
1965 close(fd);
1966
1967 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001968 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001969 unsigned int fs_size_sec, max_fs_size_sec;
1970
1971 fs_size_sec = get_fs_size(real_blkdev);
1972 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1973
1974 if (fs_size_sec > max_fs_size_sec) {
1975 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
1976 goto error_unencrypted;
1977 }
1978 }
1979
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001980 /* Get a wakelock as this may take a while, and we don't want the
1981 * device to sleep on us. We'll grab a partial wakelock, and if the UI
1982 * wants to keep the screen on, it can grab a full wakelock.
1983 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001984 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001985 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
1986
Jeff Sharkey7382f812012-08-23 14:08:59 -07001987 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07001988 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07001989 if (!sd_mnt_point) {
1990 sd_mnt_point = getenv("EXTERNAL_STORAGE");
1991 }
1992 if (!sd_mnt_point) {
1993 sd_mnt_point = "/mnt/sdcard";
1994 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07001995
1996 num_vols=vold_getNumDirectVolumes();
1997 vol_list = malloc(sizeof(struct volume_info) * num_vols);
1998 vold_getDirectVolumeList(vol_list);
1999
2000 for (i=0; i<num_vols; i++) {
2001 if (should_encrypt(&vol_list[i])) {
2002 fd = open(vol_list[i].blk_dev, O_RDONLY);
2003 if ( (vol_list[i].size = get_blkdev_size(fd)) == 0) {
2004 SLOGE("Cannot get size of block device %s\n", vol_list[i].blk_dev);
2005 goto error_unencrypted;
2006 }
2007 close(fd);
2008
Ken Sumrall3b170052011-07-11 15:38:57 -07002009 ret=vold_disableVol(vol_list[i].label);
Ken Sumrall319b1042011-06-14 14:01:55 -07002010 if ((ret < 0) && (ret != UNMOUNT_NOT_MOUNTED_ERR)) {
2011 /* -2 is returned when the device exists but is not currently mounted.
2012 * ignore the error and continue. */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002013 SLOGE("Failed to unmount volume %s\n", vol_list[i].label);
2014 goto error_unencrypted;
2015 }
2016 }
2017 }
2018
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002019 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002020 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002021 */
2022 property_set("vold.decrypt", "trigger_shutdown_framework");
2023 SLOGD("Just asked init to shut down class main\n");
2024
Ken Sumrall425524d2012-06-14 20:55:28 -07002025 if (vold_unmountAllAsecs()) {
2026 /* Just report the error. If any are left mounted,
2027 * umounting /data below will fail and handle the error.
2028 */
2029 SLOGE("Error unmounting internal asecs");
2030 }
2031
Ken Sumrall29d8da82011-05-18 17:20:07 -07002032 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
2033 if (!strcmp(fuse_sdcard, "true")) {
2034 /* This is a device using the fuse layer to emulate the sdcard semantics
2035 * on top of the userdata partition. vold does not manage it, it is managed
2036 * by the sdcard service. The sdcard service was killed by the property trigger
2037 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
2038 * unlike the case for vold managed devices above.
2039 */
2040 if (wait_and_unmount(sd_mnt_point)) {
2041 goto error_shutting_down;
2042 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002043 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002044
2045 /* Now unmount the /data partition. */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002046 if (wait_and_unmount(DATA_MNT_POINT)) {
JP Abgrall502dc742013-11-01 13:06:20 -07002047 if (allow_reboot) {
2048 goto error_shutting_down;
2049 } else {
2050 goto error_unencrypted;
2051 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002052 }
2053
2054 /* Do extra work for a better UX when doing the long inplace encryption */
2055 if (how == CRYPTO_ENABLE_INPLACE) {
2056 /* Now that /data is unmounted, we need to mount a tmpfs
2057 * /data, set a property saying we're doing inplace encryption,
2058 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002059 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002060 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002061 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002062 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002063 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002064 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002065
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002066 /* restart the framework. */
2067 /* Create necessary paths on /data */
2068 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002069 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002070 }
2071
Ken Sumrall92736ef2012-10-17 20:57:14 -07002072 /* Ugh, shutting down the framework is not synchronous, so until it
2073 * can be fixed, this horrible hack will wait a moment for it all to
2074 * shut down before proceeding. Without it, some devices cannot
2075 * restart the graphics services.
2076 */
2077 sleep(2);
2078
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002079 /* startup service classes main and late_start */
2080 property_set("vold.decrypt", "trigger_restart_min_framework");
2081 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002082
Ken Sumrall7df84122011-01-18 14:04:08 -08002083 /* OK, the framework is restarted and will soon be showing a
2084 * progress bar. Time to setup an encrypted mapping, and
2085 * either write a new filesystem, or encrypt in place updating
2086 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002087 */
2088 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002089
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002090 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002091 /* Initialize a crypt_mnt_ftr for the partition */
2092 cryptfs_init_crypt_mnt_ftr(&crypt_ftr);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002093
Ken Sumrall29d8da82011-05-18 17:20:07 -07002094 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2095 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
2096 } else {
2097 crypt_ftr.fs_size = nr_sec;
2098 }
Ken Sumralld33d4172011-02-01 00:49:13 -08002099 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence13486032014-02-03 13:28:11 -08002100 crypt_ftr.crypt_type = crypt_type;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002101 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
2102
2103 /* Make an encrypted master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07002104 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002105 SLOGE("Cannot create encrypted master key\n");
JP Abgrall502dc742013-11-01 13:06:20 -07002106 goto error_shutting_down;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002107 }
2108
2109 /* Write the key to the end of the partition */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002110 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002111
Ken Sumrall160b4d62013-04-22 12:15:39 -07002112 /* If any persistent data has been remembered, save it.
2113 * If none, create a valid empty table and save that.
2114 */
2115 if (!persist_data) {
2116 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
2117 if (pdata) {
2118 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2119 persist_data = pdata;
2120 }
2121 }
2122 if (persist_data) {
2123 save_persistent_data();
2124 }
2125
JP Abgrall7bdfa522013-11-15 13:42:56 -08002126 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002127 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
2128 "userdata");
2129
Ken Sumrall128626f2011-06-28 18:45:14 -07002130 /* The size of the userdata partition, and add in the vold volumes below */
2131 tot_encryption_size = crypt_ftr.fs_size;
2132
Ken Sumrall29d8da82011-05-18 17:20:07 -07002133 /* setup crypto mapping for all encryptable volumes handled by vold */
2134 for (i=0; i<num_vols; i++) {
2135 if (should_encrypt(&vol_list[i])) {
2136 vol_list[i].crypt_ftr = crypt_ftr; /* gotta love struct assign */
2137 vol_list[i].crypt_ftr.fs_size = vol_list[i].size;
2138 create_crypto_blk_dev(&vol_list[i].crypt_ftr, decrypted_master_key,
2139 vol_list[i].blk_dev, vol_list[i].crypto_blkdev,
2140 vol_list[i].label);
Ken Sumrall128626f2011-06-28 18:45:14 -07002141 tot_encryption_size += vol_list[i].size;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002142 }
2143 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002144
2145 if (how == CRYPTO_ENABLE_WIPE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002146 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr.fs_size, EXT4_FS);
2147 /* Encrypt all encryptable volumes handled by vold */
2148 if (!rc) {
2149 for (i=0; i<num_vols; i++) {
2150 if (should_encrypt(&vol_list[i])) {
2151 rc = cryptfs_enable_wipe(vol_list[i].crypto_blkdev,
2152 vol_list[i].crypt_ftr.fs_size, FAT_FS);
2153 }
2154 }
2155 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002156 } else if (how == CRYPTO_ENABLE_INPLACE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002157 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr.fs_size,
2158 &cur_encryption_done, tot_encryption_size);
2159 /* Encrypt all encryptable volumes handled by vold */
2160 if (!rc) {
2161 for (i=0; i<num_vols; i++) {
2162 if (should_encrypt(&vol_list[i])) {
2163 rc = cryptfs_enable_inplace(vol_list[i].crypto_blkdev,
2164 vol_list[i].blk_dev,
2165 vol_list[i].crypt_ftr.fs_size,
2166 &cur_encryption_done, tot_encryption_size);
2167 }
2168 }
2169 }
2170 if (!rc) {
2171 /* The inplace routine never actually sets the progress to 100%
2172 * due to the round down nature of integer division, so set it here */
2173 property_set("vold.encrypt_progress", "100");
2174 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002175 } else {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002176 /* Shouldn't happen */
2177 SLOGE("cryptfs_enable: internal error, unknown option\n");
JP Abgrall502dc742013-11-01 13:06:20 -07002178 goto error_shutting_down;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002179 }
2180
2181 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002182 delete_crypto_blk_dev("userdata");
2183 for (i=0; i<num_vols; i++) {
2184 if (should_encrypt(&vol_list[i])) {
2185 delete_crypto_blk_dev(vol_list[i].label);
2186 }
2187 }
2188
2189 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002190
2191 if (! rc) {
2192 /* Success */
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002193
Ken Sumralld33d4172011-02-01 00:49:13 -08002194 /* Clear the encryption in progres flag in the footer */
2195 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002196 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002197
Ken Sumrall29d8da82011-05-18 17:20:07 -07002198 sleep(2); /* Give the UI a chance to show 100% progress */
Ken Sumralladfba362013-06-04 16:37:52 -07002199 cryptfs_reboot(0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002200 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002201 char value[PROPERTY_VALUE_MAX];
2202
Ken Sumrall319369a2012-06-27 16:30:18 -07002203 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002204 if (!strcmp(value, "1")) {
2205 /* wipe data if encryption failed */
2206 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
2207 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07002208 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002209 if (fd >= 0) {
2210 write(fd, "--wipe_data", strlen("--wipe_data") + 1);
2211 close(fd);
2212 } else {
2213 SLOGE("could not open /cache/recovery/command\n");
2214 }
Ken Sumralladfba362013-06-04 16:37:52 -07002215 cryptfs_reboot(1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002216 } else {
2217 /* set property to trigger dialog */
2218 property_set("vold.encrypt_progress", "error_partially_encrypted");
2219 release_wake_lock(lockid);
2220 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002221 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002222 }
2223
Ken Sumrall3ed82362011-01-28 23:31:16 -08002224 /* hrm, the encrypt step claims success, but the reboot failed.
2225 * This should not happen.
2226 * Set the property and return. Hope the framework can deal with it.
2227 */
2228 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002229 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002230 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002231
2232error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07002233 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002234 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002235 if (lockid[0]) {
2236 release_wake_lock(lockid);
2237 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002238 return -1;
2239
2240error_shutting_down:
2241 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2242 * but the framework is stopped and not restarted to show the error, so it's up to
2243 * vold to restart the system.
2244 */
2245 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Ken Sumralladfba362013-06-04 16:37:52 -07002246 cryptfs_reboot(0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002247
2248 /* shouldn't get here */
2249 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07002250 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002251 if (lockid[0]) {
2252 release_wake_lock(lockid);
2253 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002254 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002255}
2256
Paul Lawrence13486032014-02-03 13:28:11 -08002257int cryptfs_enable(char *howarg, char *passwd, int allow_reboot)
2258{
2259 /** @todo If we keep this route (user selected encryption)
2260 * need to take a type in and pass it to here.
2261 */
2262 return cryptfs_enable_internal(howarg, CRYPT_TYPE_PASSWORD,
2263 passwd, allow_reboot);
2264}
2265
2266int cryptfs_enable_default(char *howarg, int allow_reboot)
2267{
2268 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
2269 DEFAULT_PASSWORD, allow_reboot);
2270}
2271
2272int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002273{
2274 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002275 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002276
2277 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002278 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002279 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002280 return -1;
2281 }
2282
Paul Lawrencef4faa572014-01-29 13:31:03 -08002283 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2284 SLOGE("Invalid crypt_type %d", crypt_type);
2285 return -1;
2286 }
2287
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002288 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002289 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002290 SLOGE("Error getting crypt footer and key");
2291 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002292 }
2293
Paul Lawrencef4faa572014-01-29 13:31:03 -08002294 crypt_ftr.crypt_type = crypt_type;
2295
2296 encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
2297 : newpw,
2298 crypt_ftr.salt,
2299 saved_master_key,
2300 crypt_ftr.master_key,
2301 &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002302
Jason parks70a4b3f2011-01-28 10:10:47 -06002303 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002304 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002305
2306 return 0;
2307}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002308
2309static int persist_get_key(char *fieldname, char *value)
2310{
2311 unsigned int i;
2312
2313 if (persist_data == NULL) {
2314 return -1;
2315 }
2316 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2317 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2318 /* We found it! */
2319 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2320 return 0;
2321 }
2322 }
2323
2324 return -1;
2325}
2326
2327static int persist_set_key(char *fieldname, char *value, int encrypted)
2328{
2329 unsigned int i;
2330 unsigned int num;
2331 struct crypt_mnt_ftr crypt_ftr;
2332 unsigned int max_persistent_entries;
2333 unsigned int dsize;
2334
2335 if (persist_data == NULL) {
2336 return -1;
2337 }
2338
2339 /* If encrypted, use the values from the crypt_ftr, otherwise
2340 * use the values for the current spec.
2341 */
2342 if (encrypted) {
2343 if(get_crypt_ftr_and_key(&crypt_ftr)) {
2344 return -1;
2345 }
2346 dsize = crypt_ftr.persist_data_size;
2347 } else {
2348 dsize = CRYPT_PERSIST_DATA_SIZE;
2349 }
2350 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2351 sizeof(struct crypt_persist_entry);
2352
2353 num = persist_data->persist_valid_entries;
2354
2355 for (i = 0; i < num; i++) {
2356 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2357 /* We found an existing entry, update it! */
2358 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2359 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2360 return 0;
2361 }
2362 }
2363
2364 /* We didn't find it, add it to the end, if there is room */
2365 if (persist_data->persist_valid_entries < max_persistent_entries) {
2366 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2367 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2368 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2369 persist_data->persist_valid_entries++;
2370 return 0;
2371 }
2372
2373 return -1;
2374}
2375
2376/* Return the value of the specified field. */
2377int cryptfs_getfield(char *fieldname, char *value, int len)
2378{
2379 char temp_value[PROPERTY_VALUE_MAX];
2380 char real_blkdev[MAXPATHLEN];
2381 /* 0 is success, 1 is not encrypted,
2382 * -1 is value not set, -2 is any other error
2383 */
2384 int rc = -2;
2385
2386 if (persist_data == NULL) {
2387 load_persistent_data();
2388 if (persist_data == NULL) {
2389 SLOGE("Getfield error, cannot load persistent data");
2390 goto out;
2391 }
2392 }
2393
2394 if (!persist_get_key(fieldname, temp_value)) {
2395 /* We found it, copy it to the caller's buffer and return */
2396 strlcpy(value, temp_value, len);
2397 rc = 0;
2398 } else {
2399 /* Sadness, it's not there. Return the error */
2400 rc = -1;
2401 }
2402
2403out:
2404 return rc;
2405}
2406
2407/* Set the value of the specified field. */
2408int cryptfs_setfield(char *fieldname, char *value)
2409{
2410 struct crypt_persist_data stored_pdata;
2411 struct crypt_persist_data *pdata_p;
2412 struct crypt_mnt_ftr crypt_ftr;
2413 char encrypted_state[PROPERTY_VALUE_MAX];
2414 /* 0 is success, -1 is an error */
2415 int rc = -1;
2416 int encrypted = 0;
2417
2418 if (persist_data == NULL) {
2419 load_persistent_data();
2420 if (persist_data == NULL) {
2421 SLOGE("Setfield error, cannot load persistent data");
2422 goto out;
2423 }
2424 }
2425
2426 property_get("ro.crypto.state", encrypted_state, "");
2427 if (!strcmp(encrypted_state, "encrypted") ) {
2428 encrypted = 1;
2429 }
2430
2431 if (persist_set_key(fieldname, value, encrypted)) {
2432 goto out;
2433 }
2434
2435 /* If we are running encrypted, save the persistent data now */
2436 if (encrypted) {
2437 if (save_persistent_data()) {
2438 SLOGE("Setfield error, cannot save persistent data");
2439 goto out;
2440 }
2441 }
2442
2443 rc = 0;
2444
2445out:
2446 return rc;
2447}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002448
2449/* Checks userdata. Attempt to mount the volume if default-
2450 * encrypted.
2451 * On success trigger next init phase and return 0.
2452 * Currently do not handle failure - see TODO below.
2453 */
2454int cryptfs_mount_default_encrypted(void)
2455{
2456 char decrypt_state[PROPERTY_VALUE_MAX];
2457 property_get("vold.decrypt", decrypt_state, "0");
2458 if (!strcmp(decrypt_state, "0")) {
2459 SLOGE("Not encrypted - should not call here");
2460 } else {
2461 int crypt_type = cryptfs_get_password_type();
2462 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2463 SLOGE("Bad crypt type - error");
2464 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2465 SLOGD("Password is not default - "
2466 "starting min framework to prompt");
2467 property_set("vold.decrypt", "trigger_restart_min_framework");
2468 return 0;
2469 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2470 SLOGD("Password is default - restarting filesystem");
2471 cryptfs_restart_internal(0);
2472 return 0;
2473 } else {
2474 SLOGE("Encrypted, default crypt type but can't decrypt");
2475 }
2476 }
2477
2478 /** @TODO make sure we factory wipe in this situation
2479 * In general if we got here there is no recovery
2480 */
2481 return 0;
2482}
2483
2484/* Returns type of the password, default, pattern, pin or password.
2485 */
2486int cryptfs_get_password_type(void)
2487{
2488 struct crypt_mnt_ftr crypt_ftr;
2489
2490 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2491 SLOGE("Error getting crypt footer and key\n");
2492 return -1;
2493 }
2494
2495 return crypt_ftr.crypt_type;
2496}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002497
2498int cryptfs_just_decrypted(void)
2499{
2500 int rc = just_decrypted;
2501 just_decrypted = 0;
2502 return rc;
2503}