blob: 493a6700d72d2c0db74b9e5f735fafbe62de69d1 [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>
38#include <errno.h>
Ken Sumrall3ed82362011-01-28 23:31:16 -080039#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070040#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070041#include <fs_mgr.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080042#include "cryptfs.h"
43#define LOG_TAG "Cryptfs"
44#include "cutils/log.h"
45#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070046#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080047#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070048#include <logwrap/logwrap.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070049#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070050#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070051#include "crypto_scrypt.h"
Paul Lawrenceae59fe62014-01-21 08:23:27 -080052#include "ext4_utils.h"
Paul Lawrence87999172014-02-20 12:21:31 -080053#include "CheckBattery.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080054
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070055#include <hardware/keymaster.h>
56
Mark Salyzyn3e971272014-01-21 13:27:04 -080057#define UNUSED __attribute__((unused))
58
Mark Salyzyn5eecc442014-02-12 14:16:14 -080059#define UNUSED __attribute__((unused))
60
Ken Sumrall8f869aa2010-12-03 03:47:09 -080061#define DM_CRYPT_BUF_SIZE 4096
62
Jason parks70a4b3f2011-01-28 10:10:47 -060063#define HASH_COUNT 2000
64#define KEY_LEN_BYTES 16
65#define IV_LEN_BYTES 16
66
Ken Sumrall29d8da82011-05-18 17:20:07 -070067#define KEY_IN_FOOTER "footer"
68
Paul Lawrencef4faa572014-01-29 13:31:03 -080069// "default_password" encoded into hex (d=0x64 etc)
70#define DEFAULT_PASSWORD "64656661756c745f70617373776f7264"
71
Ken Sumrall29d8da82011-05-18 17:20:07 -070072#define EXT4_FS 1
73#define FAT_FS 2
74
Ken Sumralle919efe2012-09-29 17:07:41 -070075#define TABLE_LOAD_RETRIES 10
76
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070077#define RSA_DEFAULT_KEY_SIZE 2048
78#define RSA_DEFAULT_EXPONENT 0x10001
79
Ken Sumrall8f869aa2010-12-03 03:47:09 -080080char *me = "cryptfs";
81
Jason parks70a4b3f2011-01-28 10:10:47 -060082static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070083static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060084static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -070085static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -080086
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070087static int keymaster_init(keymaster_device_t **keymaster_dev)
88{
89 int rc;
90
91 const hw_module_t* mod;
92 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
93 if (rc) {
94 ALOGE("could not find any keystore module");
95 goto out;
96 }
97
98 rc = keymaster_open(mod, keymaster_dev);
99 if (rc) {
100 ALOGE("could not open keymaster device in %s (%s)",
101 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
102 goto out;
103 }
104
105 return 0;
106
107out:
108 *keymaster_dev = NULL;
109 return rc;
110}
111
112/* Should we use keymaster? */
113static int keymaster_check_compatibility()
114{
115 keymaster_device_t *keymaster_dev = 0;
116 int rc = 0;
117
118 if (keymaster_init(&keymaster_dev)) {
119 SLOGE("Failed to init keymaster");
120 rc = -1;
121 goto out;
122 }
123
124 if (keymaster_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE) {
125 rc = 1;
126 }
127
128out:
129 keymaster_close(keymaster_dev);
130 return rc;
131}
132
133/* Create a new keymaster key and store it in this footer */
134static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
135{
136 uint8_t* key = 0;
137 keymaster_device_t *keymaster_dev = 0;
138
139 if (keymaster_init(&keymaster_dev)) {
140 SLOGE("Failed to init keymaster");
141 return -1;
142 }
143
144 int rc = 0;
145
146 keymaster_rsa_keygen_params_t params;
147 memset(&params, '\0', sizeof(params));
148 params.public_exponent = RSA_DEFAULT_EXPONENT;
149 params.modulus_size = RSA_DEFAULT_KEY_SIZE;
150
151 size_t key_size;
152 if (keymaster_dev->generate_keypair(keymaster_dev, TYPE_RSA, &params,
153 &key, &key_size)) {
154 SLOGE("Failed to generate keypair");
155 rc = -1;
156 goto out;
157 }
158
159 if (key_size > KEYMASTER_BLOB_SIZE) {
160 SLOGE("Keymaster key too large for crypto footer");
161 rc = -1;
162 goto out;
163 }
164
165 memcpy(ftr->keymaster_blob, key, key_size);
166 ftr->keymaster_blob_size = key_size;
167
168out:
169 keymaster_close(keymaster_dev);
170 free(key);
171 return rc;
172}
173
174/* This signs the given object using the keymaster key */
175static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
176 const unsigned char *object,
177 const size_t object_size,
178 unsigned char **signature,
179 size_t *signature_size)
180{
181 int rc = 0;
182 keymaster_device_t *keymaster_dev = 0;
183 if (keymaster_init(&keymaster_dev)) {
184 SLOGE("Failed to init keymaster");
185 return -1;
186 }
187
188 /* We currently set the digest type to DIGEST_NONE because it's the
189 * only supported value for keymaster. A similar issue exists with
190 * PADDING_NONE. Long term both of these should likely change.
191 */
192 keymaster_rsa_sign_params_t params;
193 params.digest_type = DIGEST_NONE;
194 params.padding_type = PADDING_NONE;
195
196 rc = keymaster_dev->sign_data(keymaster_dev,
197 &params,
198 ftr->keymaster_blob,
199 ftr->keymaster_blob_size,
200 object,
201 object_size,
202 signature,
203 signature_size);
204
205 keymaster_close(keymaster_dev);
206 return rc;
207}
208
Paul Lawrence399317e2014-03-10 13:20:50 -0700209/* Store password when userdata is successfully decrypted and mounted.
210 * Cleared by cryptfs_clear_password
211 *
212 * To avoid a double prompt at boot, we need to store the CryptKeeper
213 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
214 * Since the entire framework is torn down and rebuilt after encryption,
215 * we have to use a daemon or similar to store the password. Since vold
216 * is secured against IPC except from system processes, it seems a reasonable
217 * place to store this.
218 *
219 * password should be cleared once it has been used.
220 *
221 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800222 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700223static char* password = 0;
224static int password_expiry_time = 0;
225static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800226
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800227extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800228
Paul Lawrence87999172014-02-20 12:21:31 -0800229enum RebootType {reboot, recovery, shutdown};
230static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700231{
Paul Lawrence87999172014-02-20 12:21:31 -0800232 switch(rt) {
233 case reboot:
234 property_set(ANDROID_RB_PROPERTY, "reboot");
235 break;
236
237 case recovery:
238 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
239 break;
240
241 case shutdown:
242 property_set(ANDROID_RB_PROPERTY, "shutdown");
243 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700244 }
Paul Lawrence87999172014-02-20 12:21:31 -0800245
Ken Sumralladfba362013-06-04 16:37:52 -0700246 sleep(20);
247
248 /* Shouldn't get here, reboot should happen before sleep times out */
249 return;
250}
251
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800252static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
253{
254 memset(io, 0, dataSize);
255 io->data_size = dataSize;
256 io->data_start = sizeof(struct dm_ioctl);
257 io->version[0] = 4;
258 io->version[1] = 0;
259 io->version[2] = 0;
260 io->flags = flags;
261 if (name) {
262 strncpy(io->name, name, sizeof(io->name));
263 }
264}
265
Kenny Rootc4c70f12013-06-14 12:11:38 -0700266/**
267 * Gets the default device scrypt parameters for key derivation time tuning.
268 * The parameters should lead to about one second derivation time for the
269 * given device.
270 */
271static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
272 const int default_params[] = SCRYPT_DEFAULTS;
273 int params[] = SCRYPT_DEFAULTS;
274 char paramstr[PROPERTY_VALUE_MAX];
275 char *token;
276 char *saveptr;
277 int i;
278
279 property_get(SCRYPT_PROP, paramstr, "");
280 if (paramstr[0] != '\0') {
281 /*
282 * The token we're looking for should be three integers separated by
283 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
284 */
Kenny Root2947e342013-08-14 15:54:49 -0700285 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
286 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700287 i++, token = strtok_r(NULL, ":", &saveptr)) {
288 char *endptr;
289 params[i] = strtol(token, &endptr, 10);
290
291 /*
292 * Check that there was a valid number and it's 8-bit. If not,
293 * break out and the end check will take the default values.
294 */
295 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
296 break;
297 }
298 }
299
300 /*
301 * If there were not enough tokens or a token was malformed (not an
302 * integer), it will end up here and the default parameters can be
303 * taken.
304 */
305 if ((i != 3) || (token != NULL)) {
306 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
307 memcpy(params, default_params, sizeof(params));
308 }
309 }
310
311 ftr->N_factor = params[0];
312 ftr->r_factor = params[1];
313 ftr->p_factor = params[2];
314}
315
Ken Sumrall3ed82362011-01-28 23:31:16 -0800316static unsigned int get_fs_size(char *dev)
317{
318 int fd, block_size;
319 struct ext4_super_block sb;
320 off64_t len;
321
322 if ((fd = open(dev, O_RDONLY)) < 0) {
323 SLOGE("Cannot open device to get filesystem size ");
324 return 0;
325 }
326
327 if (lseek64(fd, 1024, SEEK_SET) < 0) {
328 SLOGE("Cannot seek to superblock");
329 return 0;
330 }
331
332 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
333 SLOGE("Cannot read superblock");
334 return 0;
335 }
336
337 close(fd);
338
339 block_size = 1024 << sb.s_log_block_size;
340 /* compute length in bytes */
341 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
342
343 /* return length in sectors */
344 return (unsigned int) (len / 512);
345}
346
Ken Sumrall160b4d62013-04-22 12:15:39 -0700347static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
348{
349 static int cached_data = 0;
350 static off64_t cached_off = 0;
351 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
352 int fd;
353 char key_loc[PROPERTY_VALUE_MAX];
354 char real_blkdev[PROPERTY_VALUE_MAX];
355 unsigned int nr_sec;
356 int rc = -1;
357
358 if (!cached_data) {
359 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
360
361 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
362 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
363 SLOGE("Cannot open real block device %s\n", real_blkdev);
364 return -1;
365 }
366
367 if ((nr_sec = get_blkdev_size(fd))) {
368 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
369 * encryption info footer and key, and plenty of bytes to spare for future
370 * growth.
371 */
372 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
373 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
374 cached_data = 1;
375 } else {
376 SLOGE("Cannot get size of block device %s\n", real_blkdev);
377 }
378 close(fd);
379 } else {
380 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
381 cached_off = 0;
382 cached_data = 1;
383 }
384 }
385
386 if (cached_data) {
387 if (metadata_fname) {
388 *metadata_fname = cached_metadata_fname;
389 }
390 if (off) {
391 *off = cached_off;
392 }
393 rc = 0;
394 }
395
396 return rc;
397}
398
Ken Sumralle8744072011-01-18 22:01:55 -0800399/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800400 * update the failed mount count but not change the key.
401 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700402static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800403{
404 int fd;
405 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700406 /* starting_off is set to the SEEK_SET offset
407 * where the crypto structure starts
408 */
409 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800410 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700411 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700412 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800413
Ken Sumrall160b4d62013-04-22 12:15:39 -0700414 if (get_crypt_ftr_info(&fname, &starting_off)) {
415 SLOGE("Unable to get crypt_ftr_info\n");
416 return -1;
417 }
418 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700419 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700420 return -1;
421 }
Ken Sumralle550f782013-08-20 13:48:23 -0700422 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
423 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700424 return -1;
425 }
426
427 /* Seek to the start of the crypt footer */
428 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
429 SLOGE("Cannot seek to real block device footer\n");
430 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800431 }
432
433 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
434 SLOGE("Cannot write real block device footer\n");
435 goto errout;
436 }
437
Ken Sumrall3be890f2011-09-14 16:53:46 -0700438 fstat(fd, &statbuf);
439 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700440 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700441 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800442 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800443 goto errout;
444 }
445 }
446
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800447 /* Success! */
448 rc = 0;
449
450errout:
451 close(fd);
452 return rc;
453
454}
455
Ken Sumrall160b4d62013-04-22 12:15:39 -0700456static inline int unix_read(int fd, void* buff, int len)
457{
458 return TEMP_FAILURE_RETRY(read(fd, buff, len));
459}
460
461static inline int unix_write(int fd, const void* buff, int len)
462{
463 return TEMP_FAILURE_RETRY(write(fd, buff, len));
464}
465
466static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
467{
468 memset(pdata, 0, len);
469 pdata->persist_magic = PERSIST_DATA_MAGIC;
470 pdata->persist_valid_entries = 0;
471}
472
473/* A routine to update the passed in crypt_ftr to the lastest version.
474 * fd is open read/write on the device that holds the crypto footer and persistent
475 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
476 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
477 */
478static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
479{
Kenny Root7434b312013-06-14 11:29:53 -0700480 int orig_major = crypt_ftr->major_version;
481 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700482
Kenny Root7434b312013-06-14 11:29:53 -0700483 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
484 struct crypt_persist_data *pdata;
485 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700486
Kenny Rootc4c70f12013-06-14 12:11:38 -0700487 SLOGW("upgrading crypto footer to 1.1");
488
Kenny Root7434b312013-06-14 11:29:53 -0700489 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
490 if (pdata == NULL) {
491 SLOGE("Cannot allocate persisent data\n");
492 return;
493 }
494 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
495
496 /* Need to initialize the persistent data area */
497 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
498 SLOGE("Cannot seek to persisent data offset\n");
499 return;
500 }
501 /* Write all zeros to the first copy, making it invalid */
502 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
503
504 /* Write a valid but empty structure to the second copy */
505 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
506 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
507
508 /* Update the footer */
509 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
510 crypt_ftr->persist_data_offset[0] = pdata_offset;
511 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
512 crypt_ftr->minor_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700513 }
514
Paul Lawrencef4faa572014-01-29 13:31:03 -0800515 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700516 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800517 /* But keep the old kdf_type.
518 * It will get updated later to KDF_SCRYPT after the password has been verified.
519 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700520 crypt_ftr->kdf_type = KDF_PBKDF2;
521 get_device_scrypt_params(crypt_ftr);
522 crypt_ftr->minor_version = 2;
523 }
524
Paul Lawrencef4faa572014-01-29 13:31:03 -0800525 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
526 SLOGW("upgrading crypto footer to 1.3");
527 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
528 crypt_ftr->minor_version = 3;
529 }
530
Kenny Root7434b312013-06-14 11:29:53 -0700531 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
532 if (lseek64(fd, offset, SEEK_SET) == -1) {
533 SLOGE("Cannot seek to crypt footer\n");
534 return;
535 }
536 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700537 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700538}
539
540
541static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800542{
543 int fd;
544 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700545 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800546 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700547 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700548 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800549
Ken Sumrall160b4d62013-04-22 12:15:39 -0700550 if (get_crypt_ftr_info(&fname, &starting_off)) {
551 SLOGE("Unable to get crypt_ftr_info\n");
552 return -1;
553 }
554 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700555 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700556 return -1;
557 }
558 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700559 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700560 return -1;
561 }
562
563 /* Make sure it's 16 Kbytes in length */
564 fstat(fd, &statbuf);
565 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
566 SLOGE("footer file %s is not the expected size!\n", fname);
567 goto errout;
568 }
569
570 /* Seek to the start of the crypt footer */
571 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
572 SLOGE("Cannot seek to real block device footer\n");
573 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800574 }
575
576 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
577 SLOGE("Cannot read real block device footer\n");
578 goto errout;
579 }
580
581 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700582 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800583 goto errout;
584 }
585
Kenny Rootc96a5f82013-06-14 12:08:28 -0700586 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
587 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
588 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800589 goto errout;
590 }
591
Kenny Rootc96a5f82013-06-14 12:08:28 -0700592 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
593 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
594 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800595 }
596
Ken Sumrall160b4d62013-04-22 12:15:39 -0700597 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
598 * copy on disk before returning.
599 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700600 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700601 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800602 }
603
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800604 /* Success! */
605 rc = 0;
606
607errout:
608 close(fd);
609 return rc;
610}
611
Ken Sumrall160b4d62013-04-22 12:15:39 -0700612static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
613{
614 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
615 crypt_ftr->persist_data_offset[1]) {
616 SLOGE("Crypt_ftr persist data regions overlap");
617 return -1;
618 }
619
620 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
621 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
622 return -1;
623 }
624
625 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
626 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
627 CRYPT_FOOTER_OFFSET) {
628 SLOGE("Persistent data extends past crypto footer");
629 return -1;
630 }
631
632 return 0;
633}
634
635static int load_persistent_data(void)
636{
637 struct crypt_mnt_ftr crypt_ftr;
638 struct crypt_persist_data *pdata = NULL;
639 char encrypted_state[PROPERTY_VALUE_MAX];
640 char *fname;
641 int found = 0;
642 int fd;
643 int ret;
644 int i;
645
646 if (persist_data) {
647 /* Nothing to do, we've already loaded or initialized it */
648 return 0;
649 }
650
651
652 /* If not encrypted, just allocate an empty table and initialize it */
653 property_get("ro.crypto.state", encrypted_state, "");
654 if (strcmp(encrypted_state, "encrypted") ) {
655 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
656 if (pdata) {
657 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
658 persist_data = pdata;
659 return 0;
660 }
661 return -1;
662 }
663
664 if(get_crypt_ftr_and_key(&crypt_ftr)) {
665 return -1;
666 }
667
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700668 if ((crypt_ftr.major_version < 1)
669 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700670 SLOGE("Crypt_ftr version doesn't support persistent data");
671 return -1;
672 }
673
674 if (get_crypt_ftr_info(&fname, NULL)) {
675 return -1;
676 }
677
678 ret = validate_persistent_data_storage(&crypt_ftr);
679 if (ret) {
680 return -1;
681 }
682
683 fd = open(fname, O_RDONLY);
684 if (fd < 0) {
685 SLOGE("Cannot open %s metadata file", fname);
686 return -1;
687 }
688
689 if (persist_data == NULL) {
690 pdata = malloc(crypt_ftr.persist_data_size);
691 if (pdata == NULL) {
692 SLOGE("Cannot allocate memory for persistent data");
693 goto err;
694 }
695 }
696
697 for (i = 0; i < 2; i++) {
698 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
699 SLOGE("Cannot seek to read persistent data on %s", fname);
700 goto err2;
701 }
702 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
703 SLOGE("Error reading persistent data on iteration %d", i);
704 goto err2;
705 }
706 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
707 found = 1;
708 break;
709 }
710 }
711
712 if (!found) {
713 SLOGI("Could not find valid persistent data, creating");
714 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
715 }
716
717 /* Success */
718 persist_data = pdata;
719 close(fd);
720 return 0;
721
722err2:
723 free(pdata);
724
725err:
726 close(fd);
727 return -1;
728}
729
730static int save_persistent_data(void)
731{
732 struct crypt_mnt_ftr crypt_ftr;
733 struct crypt_persist_data *pdata;
734 char *fname;
735 off64_t write_offset;
736 off64_t erase_offset;
737 int found = 0;
738 int fd;
739 int ret;
740
741 if (persist_data == NULL) {
742 SLOGE("No persistent data to save");
743 return -1;
744 }
745
746 if(get_crypt_ftr_and_key(&crypt_ftr)) {
747 return -1;
748 }
749
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700750 if ((crypt_ftr.major_version < 1)
751 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700752 SLOGE("Crypt_ftr version doesn't support persistent data");
753 return -1;
754 }
755
756 ret = validate_persistent_data_storage(&crypt_ftr);
757 if (ret) {
758 return -1;
759 }
760
761 if (get_crypt_ftr_info(&fname, NULL)) {
762 return -1;
763 }
764
765 fd = open(fname, O_RDWR);
766 if (fd < 0) {
767 SLOGE("Cannot open %s metadata file", fname);
768 return -1;
769 }
770
771 pdata = malloc(crypt_ftr.persist_data_size);
772 if (pdata == NULL) {
773 SLOGE("Cannot allocate persistant data");
774 goto err;
775 }
776
777 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
778 SLOGE("Cannot seek to read persistent data on %s", fname);
779 goto err2;
780 }
781
782 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
783 SLOGE("Error reading persistent data before save");
784 goto err2;
785 }
786
787 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
788 /* The first copy is the curent valid copy, so write to
789 * the second copy and erase this one */
790 write_offset = crypt_ftr.persist_data_offset[1];
791 erase_offset = crypt_ftr.persist_data_offset[0];
792 } else {
793 /* The second copy must be the valid copy, so write to
794 * the first copy, and erase the second */
795 write_offset = crypt_ftr.persist_data_offset[0];
796 erase_offset = crypt_ftr.persist_data_offset[1];
797 }
798
799 /* Write the new copy first, if successful, then erase the old copy */
800 if (lseek(fd, write_offset, SEEK_SET) < 0) {
801 SLOGE("Cannot seek to write persistent data");
802 goto err2;
803 }
804 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
805 (int) crypt_ftr.persist_data_size) {
806 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
807 SLOGE("Cannot seek to erase previous persistent data");
808 goto err2;
809 }
810 fsync(fd);
811 memset(pdata, 0, crypt_ftr.persist_data_size);
812 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
813 (int) crypt_ftr.persist_data_size) {
814 SLOGE("Cannot write to erase previous persistent data");
815 goto err2;
816 }
817 fsync(fd);
818 } else {
819 SLOGE("Cannot write to save persistent data");
820 goto err2;
821 }
822
823 /* Success */
824 free(pdata);
825 close(fd);
826 return 0;
827
828err2:
829 free(pdata);
830err:
831 close(fd);
832 return -1;
833}
834
Paul Lawrencef4faa572014-01-29 13:31:03 -0800835static int hexdigit (char c)
836{
837 if (c >= '0' && c <= '9') return c - '0';
838 c = tolower(c);
839 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
840 return -1;
841}
842
843static unsigned char* convert_hex_ascii_to_key(const char* master_key_ascii,
844 unsigned int* out_keysize)
845{
846 unsigned int i;
847 *out_keysize = 0;
848
849 size_t size = strlen (master_key_ascii);
850 if (size % 2) {
851 SLOGE("Trying to convert ascii string of odd length");
852 return NULL;
853 }
854
855 unsigned char* master_key = (unsigned char*) malloc(size / 2);
856 if (master_key == 0) {
857 SLOGE("Cannot allocate");
858 return NULL;
859 }
860
861 for (i = 0; i < size; i += 2) {
862 int high_nibble = hexdigit (master_key_ascii[i]);
863 int low_nibble = hexdigit (master_key_ascii[i + 1]);
864
865 if(high_nibble < 0 || low_nibble < 0) {
866 SLOGE("Invalid hex string");
867 free (master_key);
868 return NULL;
869 }
870
871 master_key[*out_keysize] = high_nibble * 16 + low_nibble;
872 (*out_keysize)++;
873 }
874
875 return master_key;
876}
877
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800878/* Convert a binary key of specified length into an ascii hex string equivalent,
879 * without the leading 0x and with null termination
880 */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800881static void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800882 char *master_key_ascii)
883{
884 unsigned int i, a;
885 unsigned char nibble;
886
887 for (i=0, a=0; i<keysize; i++, a+=2) {
888 /* For each byte, write out two ascii hex digits */
889 nibble = (master_key[i] >> 4) & 0xf;
890 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
891
892 nibble = master_key[i] & 0xf;
893 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
894 }
895
896 /* Add the null termination */
897 master_key_ascii[a] = '\0';
898
899}
900
Ken Sumralldb5e0262013-02-05 17:39:48 -0800901static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
902 char *real_blk_name, const char *name, int fd,
903 char *extra_params)
904{
905 char buffer[DM_CRYPT_BUF_SIZE];
906 struct dm_ioctl *io;
907 struct dm_target_spec *tgt;
908 char *crypt_params;
909 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
910 int i;
911
912 io = (struct dm_ioctl *) buffer;
913
914 /* Load the mapping table for this device */
915 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
916
917 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
918 io->target_count = 1;
919 tgt->status = 0;
920 tgt->sector_start = 0;
921 tgt->length = crypt_ftr->fs_size;
922 strcpy(tgt->target_type, "crypt");
923
924 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
925 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
926 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
927 master_key_ascii, real_blk_name, extra_params);
928 crypt_params += strlen(crypt_params) + 1;
929 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
930 tgt->next = crypt_params - buffer;
931
932 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
933 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
934 break;
935 }
936 usleep(500000);
937 }
938
939 if (i == TABLE_LOAD_RETRIES) {
940 /* We failed to load the table, return an error */
941 return -1;
942 } else {
943 return i + 1;
944 }
945}
946
947
948static int get_dm_crypt_version(int fd, const char *name, int *version)
949{
950 char buffer[DM_CRYPT_BUF_SIZE];
951 struct dm_ioctl *io;
952 struct dm_target_versions *v;
953 int i;
954
955 io = (struct dm_ioctl *) buffer;
956
957 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
958
959 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
960 return -1;
961 }
962
963 /* Iterate over the returned versions, looking for name of "crypt".
964 * When found, get and return the version.
965 */
966 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
967 while (v->next) {
968 if (! strcmp(v->name, "crypt")) {
969 /* We found the crypt driver, return the version, and get out */
970 version[0] = v->version[0];
971 version[1] = v->version[1];
972 version[2] = v->version[2];
973 return 0;
974 }
975 v = (struct dm_target_versions *)(((char *)v) + v->next);
976 }
977
978 return -1;
979}
980
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800981static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -0700982 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800983{
984 char buffer[DM_CRYPT_BUF_SIZE];
985 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
986 char *crypt_params;
987 struct dm_ioctl *io;
988 struct dm_target_spec *tgt;
989 unsigned int minor;
990 int fd;
Ken Sumralle919efe2012-09-29 17:07:41 -0700991 int i;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800992 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800993 int version[3];
994 char *extra_params;
995 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800996
997 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
998 SLOGE("Cannot open device-mapper\n");
999 goto errout;
1000 }
1001
1002 io = (struct dm_ioctl *) buffer;
1003
1004 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1005 if (ioctl(fd, DM_DEV_CREATE, io)) {
1006 SLOGE("Cannot create dm-crypt device\n");
1007 goto errout;
1008 }
1009
1010 /* Get the device status, in particular, the name of it's device file */
1011 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1012 if (ioctl(fd, DM_DEV_STATUS, io)) {
1013 SLOGE("Cannot retrieve dm-crypt device status\n");
1014 goto errout;
1015 }
1016 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1017 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1018
Ken Sumralldb5e0262013-02-05 17:39:48 -08001019 extra_params = "";
1020 if (! get_dm_crypt_version(fd, name, version)) {
1021 /* Support for allow_discards was added in version 1.11.0 */
1022 if ((version[0] >= 2) ||
1023 ((version[0] == 1) && (version[1] >= 11))) {
1024 extra_params = "1 allow_discards";
1025 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1026 }
Ken Sumralle919efe2012-09-29 17:07:41 -07001027 }
1028
Ken Sumralldb5e0262013-02-05 17:39:48 -08001029 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1030 fd, extra_params);
1031 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001032 SLOGE("Cannot load dm-crypt mapping table.\n");
1033 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001034 } else if (load_count > 1) {
1035 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001036 }
1037
1038 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -08001039 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001040
1041 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1042 SLOGE("Cannot resume the dm-crypt device\n");
1043 goto errout;
1044 }
1045
1046 /* We made it here with no errors. Woot! */
1047 retval = 0;
1048
1049errout:
1050 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1051
1052 return retval;
1053}
1054
Ken Sumrall29d8da82011-05-18 17:20:07 -07001055static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001056{
1057 int fd;
1058 char buffer[DM_CRYPT_BUF_SIZE];
1059 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001060 int retval = -1;
1061
1062 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1063 SLOGE("Cannot open device-mapper\n");
1064 goto errout;
1065 }
1066
1067 io = (struct dm_ioctl *) buffer;
1068
1069 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1070 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1071 SLOGE("Cannot remove dm-crypt device\n");
1072 goto errout;
1073 }
1074
1075 /* We made it here with no errors. Woot! */
1076 retval = 0;
1077
1078errout:
1079 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1080
1081 return retval;
1082
1083}
1084
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001085static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001086 unsigned char *ikey, void *params UNUSED)
1087{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001088 SLOGI("Using pbkdf2 for cryptfs KDF");
1089
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001090 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001091 unsigned int keysize;
1092 char* master_key = (char*)convert_hex_ascii_to_key(passwd, &keysize);
1093 if (!master_key) return -1;
1094 PKCS5_PBKDF2_HMAC_SHA1(master_key, keysize, salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001095 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001096
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001097 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001098 free (master_key);
1099 return 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001100}
1101
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001102static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001103 unsigned char *ikey, void *params)
1104{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001105 SLOGI("Using scrypt for cryptfs KDF");
1106
Kenny Rootc4c70f12013-06-14 12:11:38 -07001107 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1108
1109 int N = 1 << ftr->N_factor;
1110 int r = 1 << ftr->r_factor;
1111 int p = 1 << ftr->p_factor;
1112
1113 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001114 unsigned int keysize;
1115 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &keysize);
1116 if (!master_key) return -1;
1117 crypto_scrypt(master_key, keysize, salt, SALT_LEN, N, r, p, ikey,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001118 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001119
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001120 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001121 free (master_key);
1122 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001123}
1124
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001125static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1126 unsigned char *ikey, void *params)
1127{
1128 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1129
1130 int rc;
1131 unsigned int key_size;
1132 size_t signature_size;
1133 unsigned char* signature;
1134 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1135
1136 int N = 1 << ftr->N_factor;
1137 int r = 1 << ftr->r_factor;
1138 int p = 1 << ftr->p_factor;
1139
1140 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &key_size);
1141 if (!master_key) {
1142 SLOGE("Failed to convert passwd from hex");
1143 return -1;
1144 }
1145
1146 rc = crypto_scrypt(master_key, key_size, salt, SALT_LEN,
1147 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1148 memset(master_key, 0, key_size);
1149 free(master_key);
1150
1151 if (rc) {
1152 SLOGE("scrypt failed");
1153 return -1;
1154 }
1155
1156 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1157 &signature, &signature_size)) {
1158 SLOGE("Signing failed");
1159 return -1;
1160 }
1161
1162 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1163 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1164 free(signature);
1165
1166 if (rc) {
1167 SLOGE("scrypt failed");
1168 return -1;
1169 }
1170
1171 return 0;
1172}
1173
1174static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1175 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001176 unsigned char *encrypted_master_key,
1177 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001178{
1179 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1180 EVP_CIPHER_CTX e_ctx;
1181 int encrypted_len, final_len;
1182
1183 /* Turn the password into a key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001184 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001185
1186 switch (crypt_ftr->kdf_type) {
1187 case KDF_SCRYPT_KEYMASTER:
1188 if (keymaster_create_key(crypt_ftr)) {
1189 SLOGE("keymaster_create_key failed");
1190 return -1;
1191 }
1192
1193 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1194 SLOGE("scrypt failed");
1195 return -1;
1196 }
1197 break;
1198
1199 case KDF_SCRYPT:
1200 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1201 SLOGE("scrypt failed");
1202 return -1;
1203 }
1204 break;
1205
1206 default:
1207 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001208 return -1;
1209 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001210
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001211 /* Initialize the decryption engine */
1212 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1213 SLOGE("EVP_EncryptInit failed\n");
1214 return -1;
1215 }
1216 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001217
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001218 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001219 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
1220 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001221 SLOGE("EVP_EncryptUpdate failed\n");
1222 return -1;
1223 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001224 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001225 SLOGE("EVP_EncryptFinal failed\n");
1226 return -1;
1227 }
1228
1229 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1230 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1231 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001232 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001233
1234 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001235}
1236
JP Abgrall7bdfa522013-11-15 13:42:56 -08001237static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
Ken Sumralle8744072011-01-18 22:01:55 -08001238 unsigned char *encrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001239 unsigned char *decrypted_master_key,
1240 kdf_func kdf, void *kdf_params)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001241{
1242 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 -08001243 EVP_CIPHER_CTX d_ctx;
1244 int decrypted_len, final_len;
1245
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001246 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001247 if (kdf(passwd, salt, ikey, kdf_params)) {
1248 SLOGE("kdf failed");
1249 return -1;
1250 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001251
1252 /* Initialize the decryption engine */
1253 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1254 return -1;
1255 }
1256 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1257 /* Decrypt the master key */
1258 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1259 encrypted_master_key, KEY_LEN_BYTES)) {
1260 return -1;
1261 }
1262 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1263 return -1;
1264 }
1265
1266 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1267 return -1;
1268 } else {
1269 return 0;
1270 }
1271}
1272
Kenny Rootc4c70f12013-06-14 12:11:38 -07001273static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001274{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001275 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1276 *kdf = scrypt_keymaster;
1277 *kdf_params = ftr;
1278 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001279 *kdf = scrypt;
1280 *kdf_params = ftr;
1281 } else {
1282 *kdf = pbkdf2;
1283 *kdf_params = NULL;
1284 }
1285}
1286
JP Abgrall7bdfa522013-11-15 13:42:56 -08001287static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001288 struct crypt_mnt_ftr *crypt_ftr)
1289{
1290 kdf_func kdf;
1291 void *kdf_params;
1292 int ret;
1293
1294 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001295 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, decrypted_master_key, kdf,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001296 kdf_params);
1297 if (ret != 0) {
1298 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001299 }
1300
1301 return ret;
1302}
1303
1304static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1305 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001306 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001307 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001308 EVP_CIPHER_CTX e_ctx;
1309 int encrypted_len, final_len;
1310
1311 /* Get some random bits for a key */
1312 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001313 read(fd, key_buf, sizeof(key_buf));
1314 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001315 close(fd);
1316
1317 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001318 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001319}
1320
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001321static int wait_and_unmount(char *mountpoint)
1322{
1323 int i, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001324#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001325
1326 /* Now umount the tmpfs filesystem */
1327 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
1328 if (umount(mountpoint)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001329 if (errno == EINVAL) {
1330 /* EINVAL is returned if the directory is not a mountpoint,
1331 * i.e. there is no filesystem mounted there. So just get out.
1332 */
1333 break;
1334 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001335 sleep(1);
1336 i++;
1337 } else {
1338 break;
1339 }
1340 }
1341
1342 if (i < WAIT_UNMOUNT_COUNT) {
1343 SLOGD("unmounting %s succeeded\n", mountpoint);
1344 rc = 0;
1345 } else {
1346 SLOGE("unmounting %s failed\n", mountpoint);
1347 rc = -1;
1348 }
1349
1350 return rc;
1351}
1352
Ken Sumrallc5872692013-05-14 15:26:31 -07001353#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001354static int prep_data_fs(void)
1355{
1356 int i;
1357
1358 /* Do the prep of the /data filesystem */
1359 property_set("vold.post_fs_data_done", "0");
1360 property_set("vold.decrypt", "trigger_post_fs_data");
1361 SLOGD("Just triggered post_fs_data\n");
1362
Ken Sumrallc5872692013-05-14 15:26:31 -07001363 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001364 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001365 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001366
1367 property_get("vold.post_fs_data_done", p, "0");
1368 if (*p == '1') {
1369 break;
1370 } else {
1371 usleep(250000);
1372 }
1373 }
1374 if (i == DATA_PREP_TIMEOUT) {
1375 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001376 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001377 return -1;
1378 } else {
1379 SLOGD("post_fs_data done\n");
1380 return 0;
1381 }
1382}
1383
Paul Lawrencef4faa572014-01-29 13:31:03 -08001384static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001385{
1386 char fs_type[32];
1387 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001388 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001389 char fs_options[256];
1390 unsigned long mnt_flags;
1391 struct stat statbuf;
1392 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001393 static int restart_successful = 0;
1394
1395 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001396 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001397 SLOGE("Encrypted filesystem not validated, aborting");
1398 return -1;
1399 }
1400
1401 if (restart_successful) {
1402 SLOGE("System already restarted with encrypted disk, aborting");
1403 return -1;
1404 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001405
Paul Lawrencef4faa572014-01-29 13:31:03 -08001406 if (restart_main) {
1407 /* Here is where we shut down the framework. The init scripts
1408 * start all services in one of three classes: core, main or late_start.
1409 * On boot, we start core and main. Now, we stop main, but not core,
1410 * as core includes vold and a few other really important things that
1411 * we need to keep running. Once main has stopped, we should be able
1412 * to umount the tmpfs /data, then mount the encrypted /data.
1413 * We then restart the class main, and also the class late_start.
1414 * At the moment, I've only put a few things in late_start that I know
1415 * are not needed to bring up the framework, and that also cause problems
1416 * with unmounting the tmpfs /data, but I hope to add add more services
1417 * to the late_start class as we optimize this to decrease the delay
1418 * till the user is asked for the password to the filesystem.
1419 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001420
Paul Lawrencef4faa572014-01-29 13:31:03 -08001421 /* The init files are setup to stop the class main when vold.decrypt is
1422 * set to trigger_reset_main.
1423 */
1424 property_set("vold.decrypt", "trigger_reset_main");
1425 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001426
Paul Lawrencef4faa572014-01-29 13:31:03 -08001427 /* Ugh, shutting down the framework is not synchronous, so until it
1428 * can be fixed, this horrible hack will wait a moment for it all to
1429 * shut down before proceeding. Without it, some devices cannot
1430 * restart the graphics services.
1431 */
1432 sleep(2);
1433 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001434
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001435 /* Now that the framework is shutdown, we should be able to umount()
1436 * the tmpfs filesystem, and mount the real one.
1437 */
1438
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001439 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1440 if (strlen(crypto_blkdev) == 0) {
1441 SLOGE("fs_crypto_blkdev not set\n");
1442 return -1;
1443 }
1444
Ken Sumralle5032c42012-04-01 23:58:44 -07001445 if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001446 /* If ro.crypto.readonly is set to 1, mount the decrypted
1447 * filesystem readonly. This is used when /data is mounted by
1448 * recovery mode.
1449 */
1450 char ro_prop[PROPERTY_VALUE_MAX];
1451 property_get("ro.crypto.readonly", ro_prop, "");
1452 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1453 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1454 rec->flags |= MS_RDONLY;
1455 }
1456
Ken Sumralle5032c42012-04-01 23:58:44 -07001457 /* If that succeeded, then mount the decrypted filesystem */
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001458 fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001459
Ken Sumralle5032c42012-04-01 23:58:44 -07001460 property_set("vold.decrypt", "trigger_load_persist_props");
1461 /* Create necessary paths on /data */
1462 if (prep_data_fs()) {
1463 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001464 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001465
1466 /* startup service classes main and late_start */
1467 property_set("vold.decrypt", "trigger_restart_framework");
1468 SLOGD("Just triggered restart_framework\n");
1469
1470 /* Give it a few moments to get started */
1471 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001472 }
1473
Ken Sumrall0cc16632011-01-18 20:32:26 -08001474 if (rc == 0) {
1475 restart_successful = 1;
1476 }
1477
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001478 return rc;
1479}
1480
Paul Lawrencef4faa572014-01-29 13:31:03 -08001481int cryptfs_restart(void)
1482{
1483 /* Call internal implementation forcing a restart of main service group */
1484 return cryptfs_restart_internal(1);
1485}
1486
Mark Salyzyn3e971272014-01-21 13:27:04 -08001487static int do_crypto_complete(char *mount_point UNUSED)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001488{
1489 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001490 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001491 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001492
1493 property_get("ro.crypto.state", encrypted_state, "");
1494 if (strcmp(encrypted_state, "encrypted") ) {
1495 SLOGE("not running with encryption, aborting");
1496 return 1;
1497 }
1498
Ken Sumrall160b4d62013-04-22 12:15:39 -07001499 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001500 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001501
Ken Sumralle1a45852011-12-14 21:24:27 -08001502 /*
1503 * Only report this error if key_loc is a file and it exists.
1504 * If the device was never encrypted, and /data is not mountable for
1505 * some reason, returning 1 should prevent the UI from presenting the
1506 * a "enter password" screen, or worse, a "press button to wipe the
1507 * device" screen.
1508 */
1509 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1510 SLOGE("master key file does not exist, aborting");
1511 return 1;
1512 } else {
1513 SLOGE("Error getting crypt footer and key\n");
1514 return -1;
1515 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001516 }
1517
1518 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1519 SLOGE("Encryption process didn't finish successfully\n");
1520 return -2; /* -2 is the clue to the UI that there is no usable data on the disk,
1521 * and give the user an option to wipe the disk */
1522 }
1523
1524 /* We passed the test! We shall diminish, and return to the west */
1525 return 0;
1526}
1527
Paul Lawrencef4faa572014-01-29 13:31:03 -08001528static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1529 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001530{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001531 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001532 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001533 char crypto_blkdev[MAXPATHLEN];
1534 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001535 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001536 unsigned int orig_failed_decrypt_count;
1537 int rc;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001538 kdf_func kdf;
1539 void *kdf_params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001540 int use_keymaster = 0;
1541 int upgrade = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001542
Paul Lawrencef4faa572014-01-29 13:31:03 -08001543 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1544 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001545
Paul Lawrencef4faa572014-01-29 13:31:03 -08001546 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
1547 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001548 SLOGE("Failed to decrypt master key\n");
1549 return -1;
1550 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001551 }
1552
Paul Lawrencef4faa572014-01-29 13:31:03 -08001553 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1554
1555 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1556 real_blkdev, crypto_blkdev, label)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001557 SLOGE("Error creating decrypted block device\n");
1558 return -1;
1559 }
1560
Alex Klyubin707795a2013-05-10 15:17:07 -07001561 /* If init detects an encrypted filesystem, it writes a file for each such
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001562 * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
1563 * files and passes that data to me */
1564 /* Create a tmp mount point to try mounting the decryptd fs
1565 * Since we're here, the mount_point should be a tmpfs filesystem, so make
1566 * a directory in it to test mount the decrypted filesystem.
1567 */
1568 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1569 mkdir(tmp_mount_point, 0755);
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001570 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001571 SLOGE("Error temp mounting decrypted block device\n");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001572 delete_crypto_blk_dev(label);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001573 crypt_ftr->failed_decrypt_count++;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001574 } else {
1575 /* Success, so just umount and we'll mount it properly when we restart
1576 * the framework.
1577 */
1578 umount(tmp_mount_point);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001579 crypt_ftr->failed_decrypt_count = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001580 }
1581
Paul Lawrencef4faa572014-01-29 13:31:03 -08001582 if (orig_failed_decrypt_count != crypt_ftr->failed_decrypt_count) {
1583 put_crypt_ftr_and_key(crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001584 }
1585
Paul Lawrencef4faa572014-01-29 13:31:03 -08001586 if (crypt_ftr->failed_decrypt_count) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001587 /* We failed to mount the device, so return an error */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001588 rc = crypt_ftr->failed_decrypt_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001589
1590 } else {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001591 /* Woot! Success! Save the name of the crypto block device
1592 * so we can mount it when restarting the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001593 */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001594 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001595
1596 /* Also save a the master key so we can reencrypted the key
1597 * the key when we want to change the password on it.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001598 */
Jason parks70a4b3f2011-01-28 10:10:47 -06001599 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001600 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001601 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001602 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001603 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001604
JP Abgrall7bdfa522013-11-15 13:42:56 -08001605 /*
1606 * Upgrade if we're not using the latest KDF.
1607 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001608 use_keymaster = keymaster_check_compatibility();
1609 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1610 // Don't allow downgrade to KDF_SCRYPT
1611 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1612 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1613 upgrade = 1;
1614 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001615 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001616 upgrade = 1;
1617 }
1618
1619 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001620 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1621 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001622 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001623 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001624 }
1625 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1626 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001627 }
1628
1629 return rc;
1630}
1631
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001632/* Called by vold when it wants to undo the crypto mapping of a volume it
1633 * manages. This is usually in response to a factory reset, when we want
1634 * to undo the crypto mapping so the volume is formatted in the clear.
1635 */
1636int cryptfs_revert_volume(const char *label)
1637{
1638 return delete_crypto_blk_dev((char *)label);
1639}
1640
Ken Sumrall29d8da82011-05-18 17:20:07 -07001641/*
1642 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1643 * Setup a dm-crypt mapping, use the saved master key from
1644 * setting up the /data mapping, and return the new device path.
1645 */
1646int cryptfs_setup_volume(const char *label, int major, int minor,
1647 char *crypto_sys_path, unsigned int max_path,
1648 int *new_major, int *new_minor)
1649{
1650 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1651 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001652 struct stat statbuf;
1653 int nr_sec, fd;
1654
1655 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1656
Ken Sumrall160b4d62013-04-22 12:15:39 -07001657 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001658
1659 /* Update the fs_size field to be the size of the volume */
1660 fd = open(real_blkdev, O_RDONLY);
1661 nr_sec = get_blkdev_size(fd);
1662 close(fd);
1663 if (nr_sec == 0) {
1664 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1665 return -1;
1666 }
1667
1668 sd_crypt_ftr.fs_size = nr_sec;
1669 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1670 crypto_blkdev, label);
1671
1672 stat(crypto_blkdev, &statbuf);
1673 *new_major = MAJOR(statbuf.st_rdev);
1674 *new_minor = MINOR(statbuf.st_rdev);
1675
1676 /* Create path to sys entry for this block device */
1677 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1678
1679 return 0;
1680}
1681
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001682int cryptfs_crypto_complete(void)
1683{
1684 return do_crypto_complete("/data");
1685}
1686
Paul Lawrencef4faa572014-01-29 13:31:03 -08001687int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1688{
1689 char encrypted_state[PROPERTY_VALUE_MAX];
1690 property_get("ro.crypto.state", encrypted_state, "");
1691 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1692 SLOGE("encrypted fs already validated or not running with encryption,"
1693 " aborting");
1694 return -1;
1695 }
1696
1697 if (get_crypt_ftr_and_key(crypt_ftr)) {
1698 SLOGE("Error getting crypt footer and key");
1699 return -1;
1700 }
1701
1702 return 0;
1703}
1704
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001705int cryptfs_check_passwd(char *passwd)
1706{
Paul Lawrencef4faa572014-01-29 13:31:03 -08001707 struct crypt_mnt_ftr crypt_ftr;
1708 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001709
Paul Lawrencef4faa572014-01-29 13:31:03 -08001710 rc = check_unmounted_and_get_ftr(&crypt_ftr);
1711 if (rc)
1712 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001713
Paul Lawrencef4faa572014-01-29 13:31:03 -08001714 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
1715 DATA_MNT_POINT, "userdata");
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001716
1717 if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001718 cryptfs_clear_password();
1719 password = strdup(passwd);
1720 struct timespec now;
1721 clock_gettime(CLOCK_BOOTTIME, &now);
1722 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001723 }
1724
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001725 return rc;
1726}
1727
Ken Sumrall3ad90722011-10-04 20:38:29 -07001728int cryptfs_verify_passwd(char *passwd)
1729{
1730 struct crypt_mnt_ftr crypt_ftr;
1731 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001732 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001733 char encrypted_state[PROPERTY_VALUE_MAX];
1734 int rc;
1735
1736 property_get("ro.crypto.state", encrypted_state, "");
1737 if (strcmp(encrypted_state, "encrypted") ) {
1738 SLOGE("device not encrypted, aborting");
1739 return -2;
1740 }
1741
1742 if (!master_key_saved) {
1743 SLOGE("encrypted fs not yet mounted, aborting");
1744 return -1;
1745 }
1746
1747 if (!saved_mount_point) {
1748 SLOGE("encrypted fs failed to save mount point, aborting");
1749 return -1;
1750 }
1751
Ken Sumrall160b4d62013-04-22 12:15:39 -07001752 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001753 SLOGE("Error getting crypt footer and key\n");
1754 return -1;
1755 }
1756
1757 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1758 /* If the device has no password, then just say the password is valid */
1759 rc = 0;
1760 } else {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001761 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001762 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1763 /* They match, the password is correct */
1764 rc = 0;
1765 } else {
1766 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1767 sleep(1);
1768 rc = 1;
1769 }
1770 }
1771
1772 return rc;
1773}
1774
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001775/* Initialize a crypt_mnt_ftr structure. The keysize is
1776 * defaulted to 16 bytes, and the filesystem size to 0.
1777 * Presumably, at a minimum, the caller will update the
1778 * filesystem size and crypto_type_name after calling this function.
1779 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001780static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001781{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001782 off64_t off;
1783
1784 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001785 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001786 ftr->major_version = CURRENT_MAJOR_VERSION;
1787 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001788 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001789 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001790
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001791 switch (keymaster_check_compatibility()) {
1792 case 1:
1793 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1794 break;
1795
1796 case 0:
1797 ftr->kdf_type = KDF_SCRYPT;
1798 break;
1799
1800 default:
1801 SLOGE("keymaster_check_compatibility failed");
1802 return -1;
1803 }
1804
Kenny Rootc4c70f12013-06-14 12:11:38 -07001805 get_device_scrypt_params(ftr);
1806
Ken Sumrall160b4d62013-04-22 12:15:39 -07001807 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1808 if (get_crypt_ftr_info(NULL, &off) == 0) {
1809 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1810 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1811 ftr->persist_data_size;
1812 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001813
1814 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001815}
1816
Ken Sumrall29d8da82011-05-18 17:20:07 -07001817static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001818{
Ken Sumralle550f782013-08-20 13:48:23 -07001819 const char *args[10];
1820 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1821 int num_args;
1822 int status;
1823 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001824 int rc = -1;
1825
Ken Sumrall29d8da82011-05-18 17:20:07 -07001826 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001827 args[0] = "/system/bin/make_ext4fs";
1828 args[1] = "-a";
1829 args[2] = "/data";
1830 args[3] = "-l";
1831 snprintf(size_str, sizeof(size_str), "%lld", size * 512);
1832 args[4] = size_str;
1833 args[5] = crypto_blkdev;
1834 num_args = 6;
1835 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1836 args[0], args[1], args[2], args[3], args[4], args[5]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001837 } else if (type== FAT_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001838 args[0] = "/system/bin/newfs_msdos";
1839 args[1] = "-F";
1840 args[2] = "32";
1841 args[3] = "-O";
1842 args[4] = "android";
1843 args[5] = "-c";
1844 args[6] = "8";
1845 args[7] = "-s";
1846 snprintf(size_str, sizeof(size_str), "%lld", size);
1847 args[8] = size_str;
1848 args[9] = crypto_blkdev;
1849 num_args = 10;
1850 SLOGI("Making empty filesystem with command %s %s %s %s %s %s %s %s %s %s\n",
1851 args[0], args[1], args[2], args[3], args[4], args[5],
1852 args[6], args[7], args[8], args[9]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001853 } else {
1854 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1855 return -1;
1856 }
1857
Ken Sumralle550f782013-08-20 13:48:23 -07001858 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1859
1860 if (tmp != 0) {
1861 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001862 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07001863 if (WIFEXITED(status)) {
1864 if (WEXITSTATUS(status)) {
1865 SLOGE("Error creating filesystem on %s, exit status %d ",
1866 crypto_blkdev, WEXITSTATUS(status));
1867 } else {
1868 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
1869 rc = 0;
1870 }
1871 } else {
1872 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
1873 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001874 }
1875
1876 return rc;
1877}
1878
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001879#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08001880#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
1881#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001882
1883/* aligned 32K writes tends to make flash happy.
1884 * SD card association recommends it.
1885 */
1886#define BLOCKS_AT_A_TIME 8
1887
1888struct encryptGroupsData
1889{
1890 int realfd;
1891 int cryptofd;
1892 off64_t numblocks;
1893 off64_t one_pct, cur_pct, new_pct;
1894 off64_t blocks_already_done, tot_numblocks;
1895 char* real_blkdev, * crypto_blkdev;
1896 int count;
1897 off64_t offset;
1898 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08001899 off64_t last_written_sector;
1900 int completed;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001901};
1902
1903static void update_progress(struct encryptGroupsData* data)
1904{
1905 data->blocks_already_done++;
1906 data->new_pct = data->blocks_already_done / data->one_pct;
1907 if (data->new_pct > data->cur_pct) {
1908 char buf[8];
1909 data->cur_pct = data->new_pct;
1910 snprintf(buf, sizeof(buf), "%lld", data->cur_pct);
1911 property_set("vold.encrypt_progress", buf);
1912 }
1913}
1914
1915static int flush_outstanding_data(struct encryptGroupsData* data)
1916{
1917 if (data->count == 0) {
1918 return 0;
1919 }
1920
1921 SLOGV("Copying %d blocks at offset %llx", data->count, data->offset);
1922
1923 if (pread64(data->realfd, data->buffer,
1924 info.block_size * data->count, data->offset)
1925 <= 0) {
1926 SLOGE("Error reading real_blkdev %s for inplace encrypt",
1927 data->real_blkdev);
1928 return -1;
1929 }
1930
1931 if (pwrite64(data->cryptofd, data->buffer,
1932 info.block_size * data->count, data->offset)
1933 <= 0) {
1934 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
1935 data->crypto_blkdev);
1936 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08001937 } else {
1938 SLOGI("Encrypted %d blocks at sector %lld",
1939 data->count, data->offset / info.block_size * CRYPT_SECTOR_SIZE);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001940 }
1941
1942 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08001943 data->last_written_sector = (data->offset + data->count)
1944 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001945 return 0;
1946}
1947
1948static int encrypt_groups(struct encryptGroupsData* data)
1949{
1950 unsigned int i;
1951 u8 *block_bitmap = 0;
1952 unsigned int block;
1953 off64_t ret;
1954 int rc = -1;
1955
1956 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
1957 if (!data->buffer) {
1958 SLOGE("Failed to allocate crypto buffer");
1959 goto errout;
1960 }
1961
1962 block_bitmap = malloc(info.block_size);
1963 if (!block_bitmap) {
1964 SLOGE("failed to allocate block bitmap");
1965 goto errout;
1966 }
1967
1968 for (i = 0; i < aux_info.groups; ++i) {
1969 SLOGI("Encrypting group %d", i);
1970
1971 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
1972 u32 block_count = min(info.blocks_per_group,
1973 aux_info.len_blocks - first_block);
1974
1975 off64_t offset = (u64)info.block_size
1976 * aux_info.bg_desc[i].bg_block_bitmap;
1977
1978 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
1979 if (ret != (int)info.block_size) {
1980 SLOGE("failed to read all of block group bitmap %d", i);
1981 goto errout;
1982 }
1983
1984 offset = (u64)info.block_size * first_block;
1985
1986 data->count = 0;
1987
1988 for (block = 0; block < block_count; block++) {
1989 update_progress(data);
1990 if (bitmap_get_bit(block_bitmap, block)) {
1991 if (data->count == 0) {
1992 data->offset = offset;
1993 }
1994 data->count++;
1995 } else {
1996 if (flush_outstanding_data(data)) {
1997 goto errout;
1998 }
1999 }
2000
2001 offset += info.block_size;
2002
2003 /* Write data if we are aligned or buffer size reached */
2004 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2005 || data->count == BLOCKS_AT_A_TIME) {
2006 if (flush_outstanding_data(data)) {
2007 goto errout;
2008 }
2009 }
Paul Lawrence87999172014-02-20 12:21:31 -08002010
2011 if (!is_battery_ok()) {
2012 SLOGE("Stopping encryption due to low battery");
2013 rc = 0;
2014 goto errout;
2015 }
2016
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002017 }
2018 if (flush_outstanding_data(data)) {
2019 goto errout;
2020 }
2021 }
2022
Paul Lawrence87999172014-02-20 12:21:31 -08002023 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002024 rc = 0;
2025
2026errout:
2027 free(data->buffer);
2028 free(block_bitmap);
2029 return rc;
2030}
2031
2032static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2033 char *real_blkdev,
2034 off64_t size,
2035 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002036 off64_t tot_size,
2037 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002038{
2039 int i;
2040 struct encryptGroupsData data;
2041 int rc = -1;
2042
Paul Lawrence87999172014-02-20 12:21:31 -08002043 if (previously_encrypted_upto > *size_already_done) {
2044 SLOGD("Not fast encrypting since resuming part way through");
2045 return -1;
2046 }
2047
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002048 memset(&data, 0, sizeof(data));
2049 data.real_blkdev = real_blkdev;
2050 data.crypto_blkdev = crypto_blkdev;
2051
2052 if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
2053 SLOGE("Error opening real_blkdev %s for inplace encrypt\n",
2054 real_blkdev);
2055 goto errout;
2056 }
2057
2058 if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
2059 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n",
2060 crypto_blkdev);
2061 goto errout;
2062 }
2063
2064 if (setjmp(setjmp_env)) {
2065 SLOGE("Reading extent caused an exception");
2066 goto errout;
2067 }
2068
2069 if (read_ext(data.realfd, 0) != 0) {
2070 SLOGE("Failed to read extent");
2071 goto errout;
2072 }
2073
2074 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2075 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2076 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2077
2078 SLOGI("Encrypting filesystem in place...");
2079
2080 data.one_pct = data.tot_numblocks / 100;
2081 data.cur_pct = 0;
2082
2083 rc = encrypt_groups(&data);
2084 if (rc) {
2085 SLOGE("Error encrypting groups");
2086 goto errout;
2087 }
2088
Paul Lawrence87999172014-02-20 12:21:31 -08002089 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002090 rc = 0;
2091
2092errout:
2093 close(data.realfd);
2094 close(data.cryptofd);
2095
2096 return rc;
2097}
2098
2099static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2100 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002101 off64_t tot_size,
2102 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002103{
2104 int realfd, cryptofd;
2105 char *buf[CRYPT_INPLACE_BUFSIZE];
2106 int rc = -1;
2107 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002108 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002109 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002110
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002111 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
2112 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
2113 return -1;
2114 }
2115
2116 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
2117 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
2118 close(realfd);
2119 return -1;
2120 }
2121
2122 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2123 * The size passed in is the number of 512 byte sectors in the filesystem.
2124 * So compute the number of whole 4K blocks we should read/write,
2125 * and the remainder.
2126 */
2127 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2128 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002129 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2130 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002131
2132 SLOGE("Encrypting filesystem in place...");
2133
Paul Lawrence87999172014-02-20 12:21:31 -08002134 i = previously_encrypted_upto + 1 - *size_already_done;
2135
2136 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2137 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2138 goto errout;
2139 }
2140
2141 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2142 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2143 goto errout;
2144 }
2145
2146 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2147 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2148 SLOGE("Error reading initial sectors from real_blkdev %s for "
2149 "inplace encrypt\n", crypto_blkdev);
2150 goto errout;
2151 }
2152 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2153 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2154 "inplace encrypt\n", crypto_blkdev);
2155 goto errout;
2156 } else {
2157 SLOGI("Encrypted 1 block at %lld", i);
2158 }
2159 }
2160
Ken Sumrall29d8da82011-05-18 17:20:07 -07002161 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002162 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002163 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002164 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002165 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002166 if (new_pct > cur_pct) {
2167 char buf[8];
2168
2169 cur_pct = new_pct;
2170 snprintf(buf, sizeof(buf), "%lld", cur_pct);
2171 property_set("vold.encrypt_progress", buf);
2172 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002173 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002174 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002175 goto errout;
2176 }
2177 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002178 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2179 goto errout;
2180 } else {
2181 SLOGD("Encrypted %d block at %lld",
2182 CRYPT_SECTORS_PER_BUFSIZE,
2183 i * CRYPT_SECTORS_PER_BUFSIZE);
2184 }
2185
2186 if (!is_battery_ok()) {
2187 SLOGE("Stopping encryption due to low battery");
2188 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2189 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002190 goto errout;
2191 }
2192 }
2193
2194 /* Do any remaining sectors */
2195 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002196 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2197 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002198 goto errout;
2199 }
Paul Lawrence87999172014-02-20 12:21:31 -08002200 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2201 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002202 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002203 } else {
2204 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002205 }
2206 }
2207
Ken Sumrall29d8da82011-05-18 17:20:07 -07002208 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002209 rc = 0;
2210
2211errout:
2212 close(realfd);
2213 close(cryptofd);
2214
2215 return rc;
2216}
2217
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002218static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2219 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002220 off64_t tot_size,
2221 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002222{
Paul Lawrence87999172014-02-20 12:21:31 -08002223 if (previously_encrypted_upto) {
2224 SLOGD("Continuing encryption from %lld", previously_encrypted_upto);
2225 }
2226
2227 if (*size_already_done + size < previously_encrypted_upto) {
2228 *size_already_done += size;
2229 return 0;
2230 }
2231
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002232 if (cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002233 size, size_already_done,
2234 tot_size, previously_encrypted_upto) == 0) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002235 return 0;
2236 }
2237
2238 return cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002239 size, size_already_done, tot_size,
2240 previously_encrypted_upto);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002241}
2242
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002243#define CRYPTO_ENABLE_WIPE 1
2244#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002245
2246#define FRAMEWORK_BOOT_WAIT 60
2247
Ken Sumrall29d8da82011-05-18 17:20:07 -07002248static inline int should_encrypt(struct volume_info *volume)
2249{
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002250 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
Ken Sumrall29d8da82011-05-18 17:20:07 -07002251 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
2252}
2253
Paul Lawrence87999172014-02-20 12:21:31 -08002254static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2255{
2256 int fd = open(filename, O_RDONLY);
2257 if (fd == -1) {
2258 SLOGE("Error opening file %s", filename);
2259 return -1;
2260 }
2261
2262 char block[CRYPT_INPLACE_BUFSIZE];
2263 memset(block, 0, sizeof(block));
2264 if (unix_read(fd, block, sizeof(block)) < 0) {
2265 SLOGE("Error reading file %s", filename);
2266 close(fd);
2267 return -1;
2268 }
2269
2270 close(fd);
2271
2272 SHA256_CTX c;
2273 SHA256_Init(&c);
2274 SHA256_Update(&c, block, sizeof(block));
2275 SHA256_Final(buf, &c);
2276
2277 return 0;
2278}
2279
2280static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2281 char *crypto_blkdev, char *real_blkdev,
2282 int previously_encrypted_upto)
2283{
2284 off64_t cur_encryption_done=0, tot_encryption_size=0;
2285 int i, rc = -1;
2286
2287 if (!is_battery_ok()) {
2288 SLOGE("Stopping encryption due to low battery");
2289 return 0;
2290 }
2291
2292 /* The size of the userdata partition, and add in the vold volumes below */
2293 tot_encryption_size = crypt_ftr->fs_size;
2294
2295 if (how == CRYPTO_ENABLE_WIPE) {
2296 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, EXT4_FS);
2297 } else if (how == CRYPTO_ENABLE_INPLACE) {
2298 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2299 crypt_ftr->fs_size, &cur_encryption_done,
2300 tot_encryption_size,
2301 previously_encrypted_upto);
2302
2303 if (!rc && cur_encryption_done != (off64_t)crypt_ftr->fs_size) {
2304 crypt_ftr->encrypted_upto = cur_encryption_done;
2305 }
2306
2307 if (!rc && !crypt_ftr->encrypted_upto) {
2308 /* The inplace routine never actually sets the progress to 100% due
2309 * to the round down nature of integer division, so set it here */
2310 property_set("vold.encrypt_progress", "100");
2311 }
2312 } else {
2313 /* Shouldn't happen */
2314 SLOGE("cryptfs_enable: internal error, unknown option\n");
2315 rc = -1;
2316 }
2317
2318 return rc;
2319}
2320
Paul Lawrence13486032014-02-03 13:28:11 -08002321int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
2322 int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002323{
2324 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002325 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07002326 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002327 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07002328 int rc=-1, fd, i, ret;
Paul Lawrence87999172014-02-20 12:21:31 -08002329 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002330 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002331 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002332 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002333 char key_loc[PROPERTY_VALUE_MAX];
2334 char fuse_sdcard[PROPERTY_VALUE_MAX];
2335 char *sd_mnt_point;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002336 int num_vols;
2337 struct volume_info *vol_list = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002338 off64_t previously_encrypted_upto = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002339
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002340 if (!strcmp(howarg, "wipe")) {
2341 how = CRYPTO_ENABLE_WIPE;
2342 } else if (! strcmp(howarg, "inplace")) {
2343 how = CRYPTO_ENABLE_INPLACE;
2344 } else {
2345 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002346 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002347 }
2348
Paul Lawrence87999172014-02-20 12:21:31 -08002349 /* See if an encryption was underway and interrupted */
2350 if (how == CRYPTO_ENABLE_INPLACE
2351 && get_crypt_ftr_and_key(&crypt_ftr) == 0
2352 && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
2353 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2354 crypt_ftr.encrypted_upto = 0;
2355 }
2356
2357 property_get("ro.crypto.state", encrypted_state, "");
2358 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2359 SLOGE("Device is already running encrypted, aborting");
2360 goto error_unencrypted;
2361 }
2362
2363 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2364 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002365 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002366
Ken Sumrall3ed82362011-01-28 23:31:16 -08002367 /* Get the size of the real block device */
2368 fd = open(real_blkdev, O_RDONLY);
2369 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
2370 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2371 goto error_unencrypted;
2372 }
2373 close(fd);
2374
2375 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002376 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002377 unsigned int fs_size_sec, max_fs_size_sec;
2378
2379 fs_size_sec = get_fs_size(real_blkdev);
Paul Lawrence87999172014-02-20 12:21:31 -08002380 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002381
2382 if (fs_size_sec > max_fs_size_sec) {
2383 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2384 goto error_unencrypted;
2385 }
2386 }
2387
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002388 /* Get a wakelock as this may take a while, and we don't want the
2389 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2390 * wants to keep the screen on, it can grab a full wakelock.
2391 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002392 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002393 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2394
Jeff Sharkey7382f812012-08-23 14:08:59 -07002395 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07002396 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07002397 if (!sd_mnt_point) {
2398 sd_mnt_point = getenv("EXTERNAL_STORAGE");
2399 }
2400 if (!sd_mnt_point) {
2401 sd_mnt_point = "/mnt/sdcard";
2402 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07002403
Paul Lawrence87999172014-02-20 12:21:31 -08002404 /* TODO
2405 * Currently do not have test devices with multiple encryptable volumes.
2406 * When we acquire some, re-add support.
2407 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002408 num_vols=vold_getNumDirectVolumes();
2409 vol_list = malloc(sizeof(struct volume_info) * num_vols);
2410 vold_getDirectVolumeList(vol_list);
2411
2412 for (i=0; i<num_vols; i++) {
2413 if (should_encrypt(&vol_list[i])) {
Paul Lawrence87999172014-02-20 12:21:31 -08002414 SLOGE("Cannot encrypt if there are multiple encryptable volumes"
2415 "%s\n", vol_list[i].label);
2416 goto error_unencrypted;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002417 }
2418 }
2419
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002420 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002421 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002422 */
2423 property_set("vold.decrypt", "trigger_shutdown_framework");
2424 SLOGD("Just asked init to shut down class main\n");
2425
Ken Sumrall425524d2012-06-14 20:55:28 -07002426 if (vold_unmountAllAsecs()) {
2427 /* Just report the error. If any are left mounted,
2428 * umounting /data below will fail and handle the error.
2429 */
2430 SLOGE("Error unmounting internal asecs");
2431 }
2432
Ken Sumrall29d8da82011-05-18 17:20:07 -07002433 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
2434 if (!strcmp(fuse_sdcard, "true")) {
2435 /* This is a device using the fuse layer to emulate the sdcard semantics
2436 * on top of the userdata partition. vold does not manage it, it is managed
2437 * by the sdcard service. The sdcard service was killed by the property trigger
2438 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
2439 * unlike the case for vold managed devices above.
2440 */
2441 if (wait_and_unmount(sd_mnt_point)) {
2442 goto error_shutting_down;
2443 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002444 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002445
2446 /* Now unmount the /data partition. */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002447 if (wait_and_unmount(DATA_MNT_POINT)) {
JP Abgrall502dc742013-11-01 13:06:20 -07002448 if (allow_reboot) {
2449 goto error_shutting_down;
2450 } else {
2451 goto error_unencrypted;
2452 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002453 }
2454
2455 /* Do extra work for a better UX when doing the long inplace encryption */
2456 if (how == CRYPTO_ENABLE_INPLACE) {
2457 /* Now that /data is unmounted, we need to mount a tmpfs
2458 * /data, set a property saying we're doing inplace encryption,
2459 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002460 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002461 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002462 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002463 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002464 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002465 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002466
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002467 /* restart the framework. */
2468 /* Create necessary paths on /data */
2469 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002470 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002471 }
2472
Ken Sumrall92736ef2012-10-17 20:57:14 -07002473 /* Ugh, shutting down the framework is not synchronous, so until it
2474 * can be fixed, this horrible hack will wait a moment for it all to
2475 * shut down before proceeding. Without it, some devices cannot
2476 * restart the graphics services.
2477 */
2478 sleep(2);
2479
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002480 /* startup service classes main and late_start */
2481 property_set("vold.decrypt", "trigger_restart_min_framework");
2482 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002483
Ken Sumrall7df84122011-01-18 14:04:08 -08002484 /* OK, the framework is restarted and will soon be showing a
2485 * progress bar. Time to setup an encrypted mapping, and
2486 * either write a new filesystem, or encrypt in place updating
2487 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002488 */
2489 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002490
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002491 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002492 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence87999172014-02-20 12:21:31 -08002493 if (previously_encrypted_upto == 0) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002494 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2495 goto error_shutting_down;
2496 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002497
Paul Lawrence87999172014-02-20 12:21:31 -08002498 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2499 crypt_ftr.fs_size = nr_sec
2500 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2501 } else {
2502 crypt_ftr.fs_size = nr_sec;
2503 }
2504 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
2505 crypt_ftr.crypt_type = crypt_type;
2506 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002507
Paul Lawrence87999172014-02-20 12:21:31 -08002508 /* Make an encrypted master key */
2509 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
2510 SLOGE("Cannot create encrypted master key\n");
2511 goto error_shutting_down;
2512 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002513
Paul Lawrence87999172014-02-20 12:21:31 -08002514 /* Write the key to the end of the partition */
2515 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002516
Paul Lawrence87999172014-02-20 12:21:31 -08002517 /* If any persistent data has been remembered, save it.
2518 * If none, create a valid empty table and save that.
2519 */
2520 if (!persist_data) {
2521 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
2522 if (pdata) {
2523 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2524 persist_data = pdata;
2525 }
2526 }
2527 if (persist_data) {
2528 save_persistent_data();
2529 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002530 }
2531
JP Abgrall7bdfa522013-11-15 13:42:56 -08002532 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002533 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
2534 "userdata");
2535
Paul Lawrence87999172014-02-20 12:21:31 -08002536 /* If we are continuing, check checksums match */
2537 rc = 0;
2538 if (previously_encrypted_upto) {
2539 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2540 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002541
Paul Lawrence87999172014-02-20 12:21:31 -08002542 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2543 sizeof(hash_first_block)) != 0) {
2544 SLOGE("Checksums do not match - trigger wipe");
2545 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002546 }
2547 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002548
Paul Lawrence87999172014-02-20 12:21:31 -08002549 if (!rc) {
2550 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
2551 crypto_blkdev, real_blkdev,
2552 previously_encrypted_upto);
2553 }
2554
2555 /* Calculate checksum if we are not finished */
2556 if (!rc && crypt_ftr.encrypted_upto) {
2557 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2558 crypt_ftr.hash_first_block);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002559 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002560 SLOGE("Error calculating checksum for continuing encryption");
2561 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002562 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002563 }
2564
2565 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002566 delete_crypto_blk_dev("userdata");
Ken Sumrall29d8da82011-05-18 17:20:07 -07002567
2568 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002569
2570 if (! rc) {
2571 /* Success */
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002572
Ken Sumralld33d4172011-02-01 00:49:13 -08002573 /* Clear the encryption in progres flag in the footer */
Paul Lawrence87999172014-02-20 12:21:31 -08002574 if (!crypt_ftr.encrypted_upto) {
2575 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
2576 } else {
2577 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2578 crypt_ftr.encrypted_upto);
2579 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002580 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002581
Ken Sumrall29d8da82011-05-18 17:20:07 -07002582 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08002583 /* Partially encrypted - ensure writes are flushed to ssd */
2584
2585 if (!crypt_ftr.encrypted_upto) {
2586 cryptfs_reboot(reboot);
2587 } else {
2588 cryptfs_reboot(shutdown);
2589 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002590 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002591 char value[PROPERTY_VALUE_MAX];
2592
Ken Sumrall319369a2012-06-27 16:30:18 -07002593 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002594 if (!strcmp(value, "1")) {
2595 /* wipe data if encryption failed */
2596 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
2597 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07002598 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002599 if (fd >= 0) {
2600 write(fd, "--wipe_data", strlen("--wipe_data") + 1);
2601 close(fd);
2602 } else {
2603 SLOGE("could not open /cache/recovery/command\n");
2604 }
Paul Lawrence87999172014-02-20 12:21:31 -08002605 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002606 } else {
2607 /* set property to trigger dialog */
2608 property_set("vold.encrypt_progress", "error_partially_encrypted");
2609 release_wake_lock(lockid);
2610 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002611 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002612 }
2613
Ken Sumrall3ed82362011-01-28 23:31:16 -08002614 /* hrm, the encrypt step claims success, but the reboot failed.
2615 * This should not happen.
2616 * Set the property and return. Hope the framework can deal with it.
2617 */
2618 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002619 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002620 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002621
2622error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07002623 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002624 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002625 if (lockid[0]) {
2626 release_wake_lock(lockid);
2627 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002628 return -1;
2629
2630error_shutting_down:
2631 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2632 * but the framework is stopped and not restarted to show the error, so it's up to
2633 * vold to restart the system.
2634 */
2635 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08002636 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002637
2638 /* shouldn't get here */
2639 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07002640 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002641 if (lockid[0]) {
2642 release_wake_lock(lockid);
2643 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002644 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002645}
2646
Paul Lawrence45f10532014-04-04 18:11:56 +00002647int cryptfs_enable(char *howarg, int type, char *passwd, int allow_reboot)
Paul Lawrence13486032014-02-03 13:28:11 -08002648{
Paul Lawrence45f10532014-04-04 18:11:56 +00002649 return cryptfs_enable_internal(howarg, type, passwd, allow_reboot);
Paul Lawrence13486032014-02-03 13:28:11 -08002650}
2651
2652int cryptfs_enable_default(char *howarg, int allow_reboot)
2653{
2654 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
2655 DEFAULT_PASSWORD, allow_reboot);
2656}
2657
2658int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002659{
2660 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002661 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002662
2663 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002664 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002665 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002666 return -1;
2667 }
2668
Paul Lawrencef4faa572014-01-29 13:31:03 -08002669 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2670 SLOGE("Invalid crypt_type %d", crypt_type);
2671 return -1;
2672 }
2673
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002674 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002675 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002676 SLOGE("Error getting crypt footer and key");
2677 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002678 }
2679
Paul Lawrencef4faa572014-01-29 13:31:03 -08002680 crypt_ftr.crypt_type = crypt_type;
2681
2682 encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
2683 : newpw,
2684 crypt_ftr.salt,
2685 saved_master_key,
2686 crypt_ftr.master_key,
2687 &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002688
Jason parks70a4b3f2011-01-28 10:10:47 -06002689 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002690 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002691
2692 return 0;
2693}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002694
2695static int persist_get_key(char *fieldname, char *value)
2696{
2697 unsigned int i;
2698
2699 if (persist_data == NULL) {
2700 return -1;
2701 }
2702 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2703 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2704 /* We found it! */
2705 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2706 return 0;
2707 }
2708 }
2709
2710 return -1;
2711}
2712
2713static int persist_set_key(char *fieldname, char *value, int encrypted)
2714{
2715 unsigned int i;
2716 unsigned int num;
2717 struct crypt_mnt_ftr crypt_ftr;
2718 unsigned int max_persistent_entries;
2719 unsigned int dsize;
2720
2721 if (persist_data == NULL) {
2722 return -1;
2723 }
2724
2725 /* If encrypted, use the values from the crypt_ftr, otherwise
2726 * use the values for the current spec.
2727 */
2728 if (encrypted) {
2729 if(get_crypt_ftr_and_key(&crypt_ftr)) {
2730 return -1;
2731 }
2732 dsize = crypt_ftr.persist_data_size;
2733 } else {
2734 dsize = CRYPT_PERSIST_DATA_SIZE;
2735 }
2736 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2737 sizeof(struct crypt_persist_entry);
2738
2739 num = persist_data->persist_valid_entries;
2740
2741 for (i = 0; i < num; i++) {
2742 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2743 /* We found an existing entry, update it! */
2744 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2745 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2746 return 0;
2747 }
2748 }
2749
2750 /* We didn't find it, add it to the end, if there is room */
2751 if (persist_data->persist_valid_entries < max_persistent_entries) {
2752 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2753 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2754 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2755 persist_data->persist_valid_entries++;
2756 return 0;
2757 }
2758
2759 return -1;
2760}
2761
2762/* Return the value of the specified field. */
2763int cryptfs_getfield(char *fieldname, char *value, int len)
2764{
2765 char temp_value[PROPERTY_VALUE_MAX];
2766 char real_blkdev[MAXPATHLEN];
2767 /* 0 is success, 1 is not encrypted,
2768 * -1 is value not set, -2 is any other error
2769 */
2770 int rc = -2;
2771
2772 if (persist_data == NULL) {
2773 load_persistent_data();
2774 if (persist_data == NULL) {
2775 SLOGE("Getfield error, cannot load persistent data");
2776 goto out;
2777 }
2778 }
2779
2780 if (!persist_get_key(fieldname, temp_value)) {
2781 /* We found it, copy it to the caller's buffer and return */
2782 strlcpy(value, temp_value, len);
2783 rc = 0;
2784 } else {
2785 /* Sadness, it's not there. Return the error */
2786 rc = -1;
2787 }
2788
2789out:
2790 return rc;
2791}
2792
2793/* Set the value of the specified field. */
2794int cryptfs_setfield(char *fieldname, char *value)
2795{
2796 struct crypt_persist_data stored_pdata;
2797 struct crypt_persist_data *pdata_p;
2798 struct crypt_mnt_ftr crypt_ftr;
2799 char encrypted_state[PROPERTY_VALUE_MAX];
2800 /* 0 is success, -1 is an error */
2801 int rc = -1;
2802 int encrypted = 0;
2803
2804 if (persist_data == NULL) {
2805 load_persistent_data();
2806 if (persist_data == NULL) {
2807 SLOGE("Setfield error, cannot load persistent data");
2808 goto out;
2809 }
2810 }
2811
2812 property_get("ro.crypto.state", encrypted_state, "");
2813 if (!strcmp(encrypted_state, "encrypted") ) {
2814 encrypted = 1;
2815 }
2816
2817 if (persist_set_key(fieldname, value, encrypted)) {
2818 goto out;
2819 }
2820
2821 /* If we are running encrypted, save the persistent data now */
2822 if (encrypted) {
2823 if (save_persistent_data()) {
2824 SLOGE("Setfield error, cannot save persistent data");
2825 goto out;
2826 }
2827 }
2828
2829 rc = 0;
2830
2831out:
2832 return rc;
2833}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002834
2835/* Checks userdata. Attempt to mount the volume if default-
2836 * encrypted.
2837 * On success trigger next init phase and return 0.
2838 * Currently do not handle failure - see TODO below.
2839 */
2840int cryptfs_mount_default_encrypted(void)
2841{
2842 char decrypt_state[PROPERTY_VALUE_MAX];
2843 property_get("vold.decrypt", decrypt_state, "0");
2844 if (!strcmp(decrypt_state, "0")) {
2845 SLOGE("Not encrypted - should not call here");
2846 } else {
2847 int crypt_type = cryptfs_get_password_type();
2848 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2849 SLOGE("Bad crypt type - error");
2850 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2851 SLOGD("Password is not default - "
2852 "starting min framework to prompt");
2853 property_set("vold.decrypt", "trigger_restart_min_framework");
2854 return 0;
2855 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2856 SLOGD("Password is default - restarting filesystem");
2857 cryptfs_restart_internal(0);
2858 return 0;
2859 } else {
2860 SLOGE("Encrypted, default crypt type but can't decrypt");
2861 }
2862 }
2863
2864 /** @TODO make sure we factory wipe in this situation
2865 * In general if we got here there is no recovery
2866 */
2867 return 0;
2868}
2869
2870/* Returns type of the password, default, pattern, pin or password.
2871 */
2872int cryptfs_get_password_type(void)
2873{
2874 struct crypt_mnt_ftr crypt_ftr;
2875
2876 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2877 SLOGE("Error getting crypt footer and key\n");
2878 return -1;
2879 }
2880
2881 return crypt_ftr.crypt_type;
2882}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002883
Paul Lawrence399317e2014-03-10 13:20:50 -07002884char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002885{
Paul Lawrence399317e2014-03-10 13:20:50 -07002886 struct timespec now;
2887 clock_gettime(CLOCK_MONOTONIC, &now);
2888 if (now.tv_sec < password_expiry_time) {
2889 return password;
2890 } else {
2891 cryptfs_clear_password();
2892 return 0;
2893 }
2894}
2895
2896void cryptfs_clear_password()
2897{
2898 if (password) {
2899 size_t len = strlen(password);
2900 memset(password, 0, len);
2901 free(password);
2902 password = 0;
2903 password_expiry_time = 0;
2904 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002905}