blob: b729616968097ef90e3ac3c06f791eec6fcde433 [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>
Elliott Hughes73737162014-06-25 17:27:42 -070028#include <inttypes.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080029#include <unistd.h>
30#include <stdio.h>
31#include <sys/ioctl.h>
32#include <linux/dm-ioctl.h>
33#include <libgen.h>
34#include <stdlib.h>
35#include <sys/param.h>
36#include <string.h>
37#include <sys/mount.h>
38#include <openssl/evp.h>
39#include <errno.h>
Ken Sumrall3ed82362011-01-28 23:31:16 -080040#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070041#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070042#include <fs_mgr.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080043#include "cryptfs.h"
44#define LOG_TAG "Cryptfs"
45#include "cutils/log.h"
46#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070047#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080048#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070049#include <logwrap/logwrap.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070050#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070051#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070052#include "crypto_scrypt.h"
Paul Lawrenceae59fe62014-01-21 08:23:27 -080053#include "ext4_utils.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000054#include "f2fs_sparseblock.h"
Paul Lawrence87999172014-02-20 12:21:31 -080055#include "CheckBattery.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080056
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070057#include <hardware/keymaster.h>
58
Mark Salyzyn3e971272014-01-21 13:27:04 -080059#define UNUSED __attribute__((unused))
60
Mark Salyzyn5eecc442014-02-12 14:16:14 -080061#define UNUSED __attribute__((unused))
62
Ken Sumrall8f869aa2010-12-03 03:47:09 -080063#define DM_CRYPT_BUF_SIZE 4096
64
Jason parks70a4b3f2011-01-28 10:10:47 -060065#define HASH_COUNT 2000
66#define KEY_LEN_BYTES 16
67#define IV_LEN_BYTES 16
68
Ken Sumrall29d8da82011-05-18 17:20:07 -070069#define KEY_IN_FOOTER "footer"
70
Paul Lawrencef4faa572014-01-29 13:31:03 -080071// "default_password" encoded into hex (d=0x64 etc)
72#define DEFAULT_PASSWORD "64656661756c745f70617373776f7264"
73
Ken Sumrall29d8da82011-05-18 17:20:07 -070074#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070075#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070076
Ken Sumralle919efe2012-09-29 17:07:41 -070077#define TABLE_LOAD_RETRIES 10
78
Shawn Willden47ba10d2014-09-03 17:07:06 -060079#define RSA_KEY_SIZE 2048
80#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
81#define RSA_EXPONENT 0x10001
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070082
Ken Sumrall8f869aa2010-12-03 03:47:09 -080083char *me = "cryptfs";
84
Jason parks70a4b3f2011-01-28 10:10:47 -060085static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070086static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060087static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -070088static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -080089
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070090static int keymaster_init(keymaster_device_t **keymaster_dev)
91{
92 int rc;
93
94 const hw_module_t* mod;
95 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
96 if (rc) {
97 ALOGE("could not find any keystore module");
98 goto out;
99 }
100
101 rc = keymaster_open(mod, keymaster_dev);
102 if (rc) {
103 ALOGE("could not open keymaster device in %s (%s)",
104 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
105 goto out;
106 }
107
108 return 0;
109
110out:
111 *keymaster_dev = NULL;
112 return rc;
113}
114
115/* Should we use keymaster? */
116static int keymaster_check_compatibility()
117{
118 keymaster_device_t *keymaster_dev = 0;
119 int rc = 0;
120
121 if (keymaster_init(&keymaster_dev)) {
122 SLOGE("Failed to init keymaster");
123 rc = -1;
124 goto out;
125 }
126
Paul Lawrence8c008392014-05-06 14:02:48 -0700127 SLOGI("keymaster version is %d", keymaster_dev->common.module->module_api_version);
128
129 if (keymaster_dev->common.module->module_api_version
130 < KEYMASTER_MODULE_API_VERSION_0_3) {
131 rc = 0;
132 goto out;
133 }
134
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700135 if (keymaster_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE) {
136 rc = 1;
137 }
138
139out:
140 keymaster_close(keymaster_dev);
141 return rc;
142}
143
144/* Create a new keymaster key and store it in this footer */
145static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
146{
147 uint8_t* key = 0;
148 keymaster_device_t *keymaster_dev = 0;
149
150 if (keymaster_init(&keymaster_dev)) {
151 SLOGE("Failed to init keymaster");
152 return -1;
153 }
154
155 int rc = 0;
156
157 keymaster_rsa_keygen_params_t params;
158 memset(&params, '\0', sizeof(params));
Shawn Willden47ba10d2014-09-03 17:07:06 -0600159 params.public_exponent = RSA_EXPONENT;
160 params.modulus_size = RSA_KEY_SIZE;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700161
162 size_t key_size;
163 if (keymaster_dev->generate_keypair(keymaster_dev, TYPE_RSA, &params,
164 &key, &key_size)) {
165 SLOGE("Failed to generate keypair");
166 rc = -1;
167 goto out;
168 }
169
170 if (key_size > KEYMASTER_BLOB_SIZE) {
171 SLOGE("Keymaster key too large for crypto footer");
172 rc = -1;
173 goto out;
174 }
175
176 memcpy(ftr->keymaster_blob, key, key_size);
177 ftr->keymaster_blob_size = key_size;
178
179out:
180 keymaster_close(keymaster_dev);
181 free(key);
182 return rc;
183}
184
Shawn Willden47ba10d2014-09-03 17:07:06 -0600185/* This signs the given object using the keymaster key. It incorrectly
186 * signs a too-short value which shouldn't work but somehow does on some
187 * keymaster implementations.
188 */
189static int keymaster_sign_object_improperly(struct crypt_mnt_ftr *ftr,
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700190 const unsigned char *object,
191 const size_t object_size,
192 unsigned char **signature,
193 size_t *signature_size)
194{
195 int rc = 0;
196 keymaster_device_t *keymaster_dev = 0;
197 if (keymaster_init(&keymaster_dev)) {
198 SLOGE("Failed to init keymaster");
199 return -1;
200 }
201
202 /* We currently set the digest type to DIGEST_NONE because it's the
203 * only supported value for keymaster. A similar issue exists with
204 * PADDING_NONE. Long term both of these should likely change.
205 */
206 keymaster_rsa_sign_params_t params;
207 params.digest_type = DIGEST_NONE;
208 params.padding_type = PADDING_NONE;
209
Shawn Willden47ba10d2014-09-03 17:07:06 -0600210 SLOGE("Signing unpadded object");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700211 rc = keymaster_dev->sign_data(keymaster_dev,
212 &params,
213 ftr->keymaster_blob,
214 ftr->keymaster_blob_size,
215 object,
216 object_size,
217 signature,
218 signature_size);
219
220 keymaster_close(keymaster_dev);
221 return rc;
222}
223
Shawn Willden47ba10d2014-09-03 17:07:06 -0600224/* This signs the given object using the keymaster key, correctly. */
225static int keymaster_sign_object_properly(struct crypt_mnt_ftr *ftr,
226 const unsigned char *object,
227 const size_t object_size,
228 unsigned char **signature,
229 size_t *signature_size)
230{
231 int rc = 0;
232 keymaster_device_t *keymaster_dev = 0;
233 if (keymaster_init(&keymaster_dev)) {
234 SLOGE("Failed to init keymaster");
235 return -1;
236 }
237
238 /* We currently set the digest type to DIGEST_NONE because it's the
239 * only supported value for keymaster. A similar issue exists with
240 * PADDING_NONE. Long term both of these should likely change.
241 */
242 keymaster_rsa_sign_params_t params;
243 params.digest_type = DIGEST_NONE;
244 params.padding_type = PADDING_NONE;
245
246 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
247 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
248 memcpy(to_sign, object, min(RSA_KEY_SIZE_BYTES, object_size));
249
250 SLOGI("Signing padded object");
251 rc = keymaster_dev->sign_data(keymaster_dev,
252 &params,
253 ftr->keymaster_blob,
254 ftr->keymaster_blob_size,
255 to_sign,
256 RSA_KEY_SIZE_BYTES,
257 signature,
258 signature_size);
259
260 keymaster_close(keymaster_dev);
261 return rc;
262}
263
Paul Lawrence399317e2014-03-10 13:20:50 -0700264/* Store password when userdata is successfully decrypted and mounted.
265 * Cleared by cryptfs_clear_password
266 *
267 * To avoid a double prompt at boot, we need to store the CryptKeeper
268 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
269 * Since the entire framework is torn down and rebuilt after encryption,
270 * we have to use a daemon or similar to store the password. Since vold
271 * is secured against IPC except from system processes, it seems a reasonable
272 * place to store this.
273 *
274 * password should be cleared once it has been used.
275 *
276 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800277 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700278static char* password = 0;
279static int password_expiry_time = 0;
280static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800281
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800282extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800283
Paul Lawrence87999172014-02-20 12:21:31 -0800284enum RebootType {reboot, recovery, shutdown};
285static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700286{
Paul Lawrence87999172014-02-20 12:21:31 -0800287 switch(rt) {
288 case reboot:
289 property_set(ANDROID_RB_PROPERTY, "reboot");
290 break;
291
292 case recovery:
293 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
294 break;
295
296 case shutdown:
297 property_set(ANDROID_RB_PROPERTY, "shutdown");
298 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700299 }
Paul Lawrence87999172014-02-20 12:21:31 -0800300
Ken Sumralladfba362013-06-04 16:37:52 -0700301 sleep(20);
302
303 /* Shouldn't get here, reboot should happen before sleep times out */
304 return;
305}
306
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800307static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
308{
309 memset(io, 0, dataSize);
310 io->data_size = dataSize;
311 io->data_start = sizeof(struct dm_ioctl);
312 io->version[0] = 4;
313 io->version[1] = 0;
314 io->version[2] = 0;
315 io->flags = flags;
316 if (name) {
317 strncpy(io->name, name, sizeof(io->name));
318 }
319}
320
Kenny Rootc4c70f12013-06-14 12:11:38 -0700321/**
322 * Gets the default device scrypt parameters for key derivation time tuning.
323 * The parameters should lead to about one second derivation time for the
324 * given device.
325 */
326static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
327 const int default_params[] = SCRYPT_DEFAULTS;
328 int params[] = SCRYPT_DEFAULTS;
329 char paramstr[PROPERTY_VALUE_MAX];
330 char *token;
331 char *saveptr;
332 int i;
333
334 property_get(SCRYPT_PROP, paramstr, "");
335 if (paramstr[0] != '\0') {
336 /*
337 * The token we're looking for should be three integers separated by
338 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
339 */
Kenny Root2947e342013-08-14 15:54:49 -0700340 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
341 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700342 i++, token = strtok_r(NULL, ":", &saveptr)) {
343 char *endptr;
344 params[i] = strtol(token, &endptr, 10);
345
346 /*
347 * Check that there was a valid number and it's 8-bit. If not,
348 * break out and the end check will take the default values.
349 */
350 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
351 break;
352 }
353 }
354
355 /*
356 * If there were not enough tokens or a token was malformed (not an
357 * integer), it will end up here and the default parameters can be
358 * taken.
359 */
360 if ((i != 3) || (token != NULL)) {
361 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
362 memcpy(params, default_params, sizeof(params));
363 }
364 }
365
366 ftr->N_factor = params[0];
367 ftr->r_factor = params[1];
368 ftr->p_factor = params[2];
369}
370
Ken Sumrall3ed82362011-01-28 23:31:16 -0800371static unsigned int get_fs_size(char *dev)
372{
373 int fd, block_size;
374 struct ext4_super_block sb;
375 off64_t len;
376
377 if ((fd = open(dev, O_RDONLY)) < 0) {
378 SLOGE("Cannot open device to get filesystem size ");
379 return 0;
380 }
381
382 if (lseek64(fd, 1024, SEEK_SET) < 0) {
383 SLOGE("Cannot seek to superblock");
384 return 0;
385 }
386
387 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
388 SLOGE("Cannot read superblock");
389 return 0;
390 }
391
392 close(fd);
393
Daniel Rosenberge82df162014-08-15 22:19:23 +0000394 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
395 SLOGE("Not a valid ext4 superblock");
396 return 0;
397 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800398 block_size = 1024 << sb.s_log_block_size;
399 /* compute length in bytes */
400 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
401
402 /* return length in sectors */
403 return (unsigned int) (len / 512);
404}
405
Ken Sumrall160b4d62013-04-22 12:15:39 -0700406static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
407{
408 static int cached_data = 0;
409 static off64_t cached_off = 0;
410 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
411 int fd;
412 char key_loc[PROPERTY_VALUE_MAX];
413 char real_blkdev[PROPERTY_VALUE_MAX];
414 unsigned int nr_sec;
415 int rc = -1;
416
417 if (!cached_data) {
418 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
419
420 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
421 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
422 SLOGE("Cannot open real block device %s\n", real_blkdev);
423 return -1;
424 }
425
426 if ((nr_sec = get_blkdev_size(fd))) {
427 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
428 * encryption info footer and key, and plenty of bytes to spare for future
429 * growth.
430 */
431 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
432 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
433 cached_data = 1;
434 } else {
435 SLOGE("Cannot get size of block device %s\n", real_blkdev);
436 }
437 close(fd);
438 } else {
439 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
440 cached_off = 0;
441 cached_data = 1;
442 }
443 }
444
445 if (cached_data) {
446 if (metadata_fname) {
447 *metadata_fname = cached_metadata_fname;
448 }
449 if (off) {
450 *off = cached_off;
451 }
452 rc = 0;
453 }
454
455 return rc;
456}
457
Ken Sumralle8744072011-01-18 22:01:55 -0800458/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800459 * update the failed mount count but not change the key.
460 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700461static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800462{
463 int fd;
464 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700465 /* starting_off is set to the SEEK_SET offset
466 * where the crypto structure starts
467 */
468 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800469 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700470 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700471 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800472
Ken Sumrall160b4d62013-04-22 12:15:39 -0700473 if (get_crypt_ftr_info(&fname, &starting_off)) {
474 SLOGE("Unable to get crypt_ftr_info\n");
475 return -1;
476 }
477 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700478 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700479 return -1;
480 }
Ken Sumralle550f782013-08-20 13:48:23 -0700481 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
482 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700483 return -1;
484 }
485
486 /* Seek to the start of the crypt footer */
487 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
488 SLOGE("Cannot seek to real block device footer\n");
489 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800490 }
491
492 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
493 SLOGE("Cannot write real block device footer\n");
494 goto errout;
495 }
496
Ken Sumrall3be890f2011-09-14 16:53:46 -0700497 fstat(fd, &statbuf);
498 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700499 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700500 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800501 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800502 goto errout;
503 }
504 }
505
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800506 /* Success! */
507 rc = 0;
508
509errout:
510 close(fd);
511 return rc;
512
513}
514
Ken Sumrall160b4d62013-04-22 12:15:39 -0700515static inline int unix_read(int fd, void* buff, int len)
516{
517 return TEMP_FAILURE_RETRY(read(fd, buff, len));
518}
519
520static inline int unix_write(int fd, const void* buff, int len)
521{
522 return TEMP_FAILURE_RETRY(write(fd, buff, len));
523}
524
525static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
526{
527 memset(pdata, 0, len);
528 pdata->persist_magic = PERSIST_DATA_MAGIC;
529 pdata->persist_valid_entries = 0;
530}
531
532/* A routine to update the passed in crypt_ftr to the lastest version.
533 * fd is open read/write on the device that holds the crypto footer and persistent
534 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
535 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
536 */
537static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
538{
Kenny Root7434b312013-06-14 11:29:53 -0700539 int orig_major = crypt_ftr->major_version;
540 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700541
Kenny Root7434b312013-06-14 11:29:53 -0700542 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
543 struct crypt_persist_data *pdata;
544 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700545
Kenny Rootc4c70f12013-06-14 12:11:38 -0700546 SLOGW("upgrading crypto footer to 1.1");
547
Kenny Root7434b312013-06-14 11:29:53 -0700548 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
549 if (pdata == NULL) {
550 SLOGE("Cannot allocate persisent data\n");
551 return;
552 }
553 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
554
555 /* Need to initialize the persistent data area */
556 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
557 SLOGE("Cannot seek to persisent data offset\n");
558 return;
559 }
560 /* Write all zeros to the first copy, making it invalid */
561 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
562
563 /* Write a valid but empty structure to the second copy */
564 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
565 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
566
567 /* Update the footer */
568 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
569 crypt_ftr->persist_data_offset[0] = pdata_offset;
570 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
571 crypt_ftr->minor_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700572 }
573
Paul Lawrencef4faa572014-01-29 13:31:03 -0800574 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700575 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800576 /* But keep the old kdf_type.
577 * It will get updated later to KDF_SCRYPT after the password has been verified.
578 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700579 crypt_ftr->kdf_type = KDF_PBKDF2;
580 get_device_scrypt_params(crypt_ftr);
581 crypt_ftr->minor_version = 2;
582 }
583
Paul Lawrencef4faa572014-01-29 13:31:03 -0800584 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
585 SLOGW("upgrading crypto footer to 1.3");
586 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
587 crypt_ftr->minor_version = 3;
588 }
589
Kenny Root7434b312013-06-14 11:29:53 -0700590 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
591 if (lseek64(fd, offset, SEEK_SET) == -1) {
592 SLOGE("Cannot seek to crypt footer\n");
593 return;
594 }
595 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700596 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700597}
598
599
600static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800601{
602 int fd;
603 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700604 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800605 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700606 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700607 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800608
Ken Sumrall160b4d62013-04-22 12:15:39 -0700609 if (get_crypt_ftr_info(&fname, &starting_off)) {
610 SLOGE("Unable to get crypt_ftr_info\n");
611 return -1;
612 }
613 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700614 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700615 return -1;
616 }
617 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700618 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700619 return -1;
620 }
621
622 /* Make sure it's 16 Kbytes in length */
623 fstat(fd, &statbuf);
624 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
625 SLOGE("footer file %s is not the expected size!\n", fname);
626 goto errout;
627 }
628
629 /* Seek to the start of the crypt footer */
630 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
631 SLOGE("Cannot seek to real block device footer\n");
632 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800633 }
634
635 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
636 SLOGE("Cannot read real block device footer\n");
637 goto errout;
638 }
639
640 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700641 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800642 goto errout;
643 }
644
Kenny Rootc96a5f82013-06-14 12:08:28 -0700645 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
646 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
647 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800648 goto errout;
649 }
650
Kenny Rootc96a5f82013-06-14 12:08:28 -0700651 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
652 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
653 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800654 }
655
Ken Sumrall160b4d62013-04-22 12:15:39 -0700656 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
657 * copy on disk before returning.
658 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700659 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700660 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800661 }
662
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800663 /* Success! */
664 rc = 0;
665
666errout:
667 close(fd);
668 return rc;
669}
670
Ken Sumrall160b4d62013-04-22 12:15:39 -0700671static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
672{
673 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
674 crypt_ftr->persist_data_offset[1]) {
675 SLOGE("Crypt_ftr persist data regions overlap");
676 return -1;
677 }
678
679 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
680 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
681 return -1;
682 }
683
684 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
685 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
686 CRYPT_FOOTER_OFFSET) {
687 SLOGE("Persistent data extends past crypto footer");
688 return -1;
689 }
690
691 return 0;
692}
693
694static int load_persistent_data(void)
695{
696 struct crypt_mnt_ftr crypt_ftr;
697 struct crypt_persist_data *pdata = NULL;
698 char encrypted_state[PROPERTY_VALUE_MAX];
699 char *fname;
700 int found = 0;
701 int fd;
702 int ret;
703 int i;
704
705 if (persist_data) {
706 /* Nothing to do, we've already loaded or initialized it */
707 return 0;
708 }
709
710
711 /* If not encrypted, just allocate an empty table and initialize it */
712 property_get("ro.crypto.state", encrypted_state, "");
713 if (strcmp(encrypted_state, "encrypted") ) {
714 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
715 if (pdata) {
716 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
717 persist_data = pdata;
718 return 0;
719 }
720 return -1;
721 }
722
723 if(get_crypt_ftr_and_key(&crypt_ftr)) {
724 return -1;
725 }
726
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700727 if ((crypt_ftr.major_version < 1)
728 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700729 SLOGE("Crypt_ftr version doesn't support persistent data");
730 return -1;
731 }
732
733 if (get_crypt_ftr_info(&fname, NULL)) {
734 return -1;
735 }
736
737 ret = validate_persistent_data_storage(&crypt_ftr);
738 if (ret) {
739 return -1;
740 }
741
742 fd = open(fname, O_RDONLY);
743 if (fd < 0) {
744 SLOGE("Cannot open %s metadata file", fname);
745 return -1;
746 }
747
748 if (persist_data == NULL) {
749 pdata = malloc(crypt_ftr.persist_data_size);
750 if (pdata == NULL) {
751 SLOGE("Cannot allocate memory for persistent data");
752 goto err;
753 }
754 }
755
756 for (i = 0; i < 2; i++) {
757 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
758 SLOGE("Cannot seek to read persistent data on %s", fname);
759 goto err2;
760 }
761 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
762 SLOGE("Error reading persistent data on iteration %d", i);
763 goto err2;
764 }
765 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
766 found = 1;
767 break;
768 }
769 }
770
771 if (!found) {
772 SLOGI("Could not find valid persistent data, creating");
773 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
774 }
775
776 /* Success */
777 persist_data = pdata;
778 close(fd);
779 return 0;
780
781err2:
782 free(pdata);
783
784err:
785 close(fd);
786 return -1;
787}
788
789static int save_persistent_data(void)
790{
791 struct crypt_mnt_ftr crypt_ftr;
792 struct crypt_persist_data *pdata;
793 char *fname;
794 off64_t write_offset;
795 off64_t erase_offset;
796 int found = 0;
797 int fd;
798 int ret;
799
800 if (persist_data == NULL) {
801 SLOGE("No persistent data to save");
802 return -1;
803 }
804
805 if(get_crypt_ftr_and_key(&crypt_ftr)) {
806 return -1;
807 }
808
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700809 if ((crypt_ftr.major_version < 1)
810 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700811 SLOGE("Crypt_ftr version doesn't support persistent data");
812 return -1;
813 }
814
815 ret = validate_persistent_data_storage(&crypt_ftr);
816 if (ret) {
817 return -1;
818 }
819
820 if (get_crypt_ftr_info(&fname, NULL)) {
821 return -1;
822 }
823
824 fd = open(fname, O_RDWR);
825 if (fd < 0) {
826 SLOGE("Cannot open %s metadata file", fname);
827 return -1;
828 }
829
830 pdata = malloc(crypt_ftr.persist_data_size);
831 if (pdata == NULL) {
832 SLOGE("Cannot allocate persistant data");
833 goto err;
834 }
835
836 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
837 SLOGE("Cannot seek to read persistent data on %s", fname);
838 goto err2;
839 }
840
841 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
842 SLOGE("Error reading persistent data before save");
843 goto err2;
844 }
845
846 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
847 /* The first copy is the curent valid copy, so write to
848 * the second copy and erase this one */
849 write_offset = crypt_ftr.persist_data_offset[1];
850 erase_offset = crypt_ftr.persist_data_offset[0];
851 } else {
852 /* The second copy must be the valid copy, so write to
853 * the first copy, and erase the second */
854 write_offset = crypt_ftr.persist_data_offset[0];
855 erase_offset = crypt_ftr.persist_data_offset[1];
856 }
857
858 /* Write the new copy first, if successful, then erase the old copy */
859 if (lseek(fd, write_offset, SEEK_SET) < 0) {
860 SLOGE("Cannot seek to write persistent data");
861 goto err2;
862 }
863 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
864 (int) crypt_ftr.persist_data_size) {
865 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
866 SLOGE("Cannot seek to erase previous persistent data");
867 goto err2;
868 }
869 fsync(fd);
870 memset(pdata, 0, crypt_ftr.persist_data_size);
871 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
872 (int) crypt_ftr.persist_data_size) {
873 SLOGE("Cannot write to erase previous persistent data");
874 goto err2;
875 }
876 fsync(fd);
877 } else {
878 SLOGE("Cannot write to save persistent data");
879 goto err2;
880 }
881
882 /* Success */
883 free(pdata);
884 close(fd);
885 return 0;
886
887err2:
888 free(pdata);
889err:
890 close(fd);
891 return -1;
892}
893
Paul Lawrencef4faa572014-01-29 13:31:03 -0800894static int hexdigit (char c)
895{
896 if (c >= '0' && c <= '9') return c - '0';
897 c = tolower(c);
898 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
899 return -1;
900}
901
902static unsigned char* convert_hex_ascii_to_key(const char* master_key_ascii,
903 unsigned int* out_keysize)
904{
905 unsigned int i;
906 *out_keysize = 0;
907
908 size_t size = strlen (master_key_ascii);
909 if (size % 2) {
910 SLOGE("Trying to convert ascii string of odd length");
911 return NULL;
912 }
913
914 unsigned char* master_key = (unsigned char*) malloc(size / 2);
915 if (master_key == 0) {
916 SLOGE("Cannot allocate");
917 return NULL;
918 }
919
920 for (i = 0; i < size; i += 2) {
921 int high_nibble = hexdigit (master_key_ascii[i]);
922 int low_nibble = hexdigit (master_key_ascii[i + 1]);
923
924 if(high_nibble < 0 || low_nibble < 0) {
925 SLOGE("Invalid hex string");
926 free (master_key);
927 return NULL;
928 }
929
930 master_key[*out_keysize] = high_nibble * 16 + low_nibble;
931 (*out_keysize)++;
932 }
933
934 return master_key;
935}
936
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800937/* Convert a binary key of specified length into an ascii hex string equivalent,
938 * without the leading 0x and with null termination
939 */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800940static void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800941 char *master_key_ascii)
942{
943 unsigned int i, a;
944 unsigned char nibble;
945
946 for (i=0, a=0; i<keysize; i++, a+=2) {
947 /* For each byte, write out two ascii hex digits */
948 nibble = (master_key[i] >> 4) & 0xf;
949 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
950
951 nibble = master_key[i] & 0xf;
952 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
953 }
954
955 /* Add the null termination */
956 master_key_ascii[a] = '\0';
957
958}
959
Ken Sumralldb5e0262013-02-05 17:39:48 -0800960static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
961 char *real_blk_name, const char *name, int fd,
962 char *extra_params)
963{
964 char buffer[DM_CRYPT_BUF_SIZE];
965 struct dm_ioctl *io;
966 struct dm_target_spec *tgt;
967 char *crypt_params;
968 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
969 int i;
970
971 io = (struct dm_ioctl *) buffer;
972
973 /* Load the mapping table for this device */
974 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
975
976 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
977 io->target_count = 1;
978 tgt->status = 0;
979 tgt->sector_start = 0;
980 tgt->length = crypt_ftr->fs_size;
981 strcpy(tgt->target_type, "crypt");
982
983 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
984 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
985 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
986 master_key_ascii, real_blk_name, extra_params);
987 crypt_params += strlen(crypt_params) + 1;
988 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
989 tgt->next = crypt_params - buffer;
990
991 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
992 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
993 break;
994 }
995 usleep(500000);
996 }
997
998 if (i == TABLE_LOAD_RETRIES) {
999 /* We failed to load the table, return an error */
1000 return -1;
1001 } else {
1002 return i + 1;
1003 }
1004}
1005
1006
1007static int get_dm_crypt_version(int fd, const char *name, int *version)
1008{
1009 char buffer[DM_CRYPT_BUF_SIZE];
1010 struct dm_ioctl *io;
1011 struct dm_target_versions *v;
1012 int i;
1013
1014 io = (struct dm_ioctl *) buffer;
1015
1016 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1017
1018 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1019 return -1;
1020 }
1021
1022 /* Iterate over the returned versions, looking for name of "crypt".
1023 * When found, get and return the version.
1024 */
1025 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1026 while (v->next) {
1027 if (! strcmp(v->name, "crypt")) {
1028 /* We found the crypt driver, return the version, and get out */
1029 version[0] = v->version[0];
1030 version[1] = v->version[1];
1031 version[2] = v->version[2];
1032 return 0;
1033 }
1034 v = (struct dm_target_versions *)(((char *)v) + v->next);
1035 }
1036
1037 return -1;
1038}
1039
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001040static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -07001041 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001042{
1043 char buffer[DM_CRYPT_BUF_SIZE];
1044 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
1045 char *crypt_params;
1046 struct dm_ioctl *io;
1047 struct dm_target_spec *tgt;
1048 unsigned int minor;
1049 int fd;
Ken Sumralle919efe2012-09-29 17:07:41 -07001050 int i;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001051 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001052 int version[3];
1053 char *extra_params;
1054 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001055
1056 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1057 SLOGE("Cannot open device-mapper\n");
1058 goto errout;
1059 }
1060
1061 io = (struct dm_ioctl *) buffer;
1062
1063 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1064 if (ioctl(fd, DM_DEV_CREATE, io)) {
1065 SLOGE("Cannot create dm-crypt device\n");
1066 goto errout;
1067 }
1068
1069 /* Get the device status, in particular, the name of it's device file */
1070 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1071 if (ioctl(fd, DM_DEV_STATUS, io)) {
1072 SLOGE("Cannot retrieve dm-crypt device status\n");
1073 goto errout;
1074 }
1075 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1076 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1077
Ken Sumralldb5e0262013-02-05 17:39:48 -08001078 extra_params = "";
1079 if (! get_dm_crypt_version(fd, name, version)) {
1080 /* Support for allow_discards was added in version 1.11.0 */
1081 if ((version[0] >= 2) ||
1082 ((version[0] == 1) && (version[1] >= 11))) {
1083 extra_params = "1 allow_discards";
1084 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1085 }
Ken Sumralle919efe2012-09-29 17:07:41 -07001086 }
1087
Ken Sumralldb5e0262013-02-05 17:39:48 -08001088 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1089 fd, extra_params);
1090 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001091 SLOGE("Cannot load dm-crypt mapping table.\n");
1092 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001093 } else if (load_count > 1) {
1094 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001095 }
1096
1097 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -08001098 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001099
1100 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1101 SLOGE("Cannot resume the dm-crypt device\n");
1102 goto errout;
1103 }
1104
1105 /* We made it here with no errors. Woot! */
1106 retval = 0;
1107
1108errout:
1109 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1110
1111 return retval;
1112}
1113
Ken Sumrall29d8da82011-05-18 17:20:07 -07001114static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001115{
1116 int fd;
1117 char buffer[DM_CRYPT_BUF_SIZE];
1118 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001119 int retval = -1;
1120
1121 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1122 SLOGE("Cannot open device-mapper\n");
1123 goto errout;
1124 }
1125
1126 io = (struct dm_ioctl *) buffer;
1127
1128 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1129 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1130 SLOGE("Cannot remove dm-crypt device\n");
1131 goto errout;
1132 }
1133
1134 /* We made it here with no errors. Woot! */
1135 retval = 0;
1136
1137errout:
1138 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1139
1140 return retval;
1141
1142}
1143
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001144static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001145 unsigned char *ikey, void *params UNUSED)
1146{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001147 SLOGI("Using pbkdf2 for cryptfs KDF");
1148
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001149 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001150 unsigned int keysize;
1151 char* master_key = (char*)convert_hex_ascii_to_key(passwd, &keysize);
1152 if (!master_key) return -1;
1153 PKCS5_PBKDF2_HMAC_SHA1(master_key, keysize, salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001154 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001155
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001156 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001157 free (master_key);
1158 return 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001159}
1160
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001161static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001162 unsigned char *ikey, void *params)
1163{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001164 SLOGI("Using scrypt for cryptfs KDF");
1165
Kenny Rootc4c70f12013-06-14 12:11:38 -07001166 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1167
1168 int N = 1 << ftr->N_factor;
1169 int r = 1 << ftr->r_factor;
1170 int p = 1 << ftr->p_factor;
1171
1172 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001173 unsigned int keysize;
1174 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &keysize);
1175 if (!master_key) return -1;
1176 crypto_scrypt(master_key, keysize, salt, SALT_LEN, N, r, p, ikey,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001177 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001178
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001179 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001180 free (master_key);
1181 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001182}
1183
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001184static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1185 unsigned char *ikey, void *params)
1186{
1187 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1188
1189 int rc;
1190 unsigned int key_size;
1191 size_t signature_size;
1192 unsigned char* signature;
1193 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1194
1195 int N = 1 << ftr->N_factor;
1196 int r = 1 << ftr->r_factor;
1197 int p = 1 << ftr->p_factor;
1198
1199 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &key_size);
1200 if (!master_key) {
1201 SLOGE("Failed to convert passwd from hex");
1202 return -1;
1203 }
1204
1205 rc = crypto_scrypt(master_key, key_size, salt, SALT_LEN,
1206 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1207 memset(master_key, 0, key_size);
1208 free(master_key);
1209
1210 if (rc) {
1211 SLOGE("scrypt failed");
1212 return -1;
1213 }
1214
Shawn Willden47ba10d2014-09-03 17:07:06 -06001215 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER_IMPROPER) {
1216 if (keymaster_sign_object_improperly(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1217 &signature, &signature_size)) {
1218 SLOGE("Signing failed");
1219 return -1;
1220 }
1221 } else {
1222 if (keymaster_sign_object_properly(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1223 &signature, &signature_size)) {
1224 SLOGE("Signing failed");
1225 return -1;
1226 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001227 }
1228
1229 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1230 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1231 free(signature);
1232
1233 if (rc) {
1234 SLOGE("scrypt failed");
1235 return -1;
1236 }
1237
1238 return 0;
1239}
1240
1241static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1242 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001243 unsigned char *encrypted_master_key,
1244 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001245{
1246 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1247 EVP_CIPHER_CTX e_ctx;
1248 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001249 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001250
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001251 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001252 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001253
1254 switch (crypt_ftr->kdf_type) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001255 case KDF_SCRYPT_KEYMASTER_IMPROPER:
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001256 case KDF_SCRYPT_KEYMASTER:
1257 if (keymaster_create_key(crypt_ftr)) {
1258 SLOGE("keymaster_create_key failed");
1259 return -1;
1260 }
1261
1262 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1263 SLOGE("scrypt failed");
1264 return -1;
1265 }
1266 break;
1267
1268 case KDF_SCRYPT:
1269 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1270 SLOGE("scrypt failed");
1271 return -1;
1272 }
1273 break;
1274
1275 default:
1276 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001277 return -1;
1278 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001279
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001280 /* Initialize the decryption engine */
1281 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1282 SLOGE("EVP_EncryptInit failed\n");
1283 return -1;
1284 }
1285 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001286
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001287 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001288 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
1289 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001290 SLOGE("EVP_EncryptUpdate failed\n");
1291 return -1;
1292 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001293 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001294 SLOGE("EVP_EncryptFinal failed\n");
1295 return -1;
1296 }
1297
1298 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1299 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1300 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001301 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001302
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001303 /* Store the scrypt of the intermediate key, so we can validate if it's a
1304 password error or mount error when things go wrong.
1305 Note there's no need to check for errors, since if this is incorrect, we
1306 simply won't wipe userdata, which is the correct default behavior
1307 */
1308 int N = 1 << crypt_ftr->N_factor;
1309 int r = 1 << crypt_ftr->r_factor;
1310 int p = 1 << crypt_ftr->p_factor;
1311
1312 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1313 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1314 crypt_ftr->scrypted_intermediate_key,
1315 sizeof(crypt_ftr->scrypted_intermediate_key));
1316
1317 if (rc) {
1318 SLOGE("encrypt_master_key: crypto_scrypt failed");
1319 }
1320
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001321 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001322}
1323
JP Abgrall7bdfa522013-11-15 13:42:56 -08001324static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001325 unsigned char *encrypted_master_key,
1326 unsigned char *decrypted_master_key,
1327 kdf_func kdf, void *kdf_params,
1328 unsigned char** intermediate_key,
1329 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001330{
1331 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 -08001332 EVP_CIPHER_CTX d_ctx;
1333 int decrypted_len, final_len;
1334
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001335 /* Turn the password into an intermediate key and IV that can decrypt the
1336 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001337 if (kdf(passwd, salt, ikey, kdf_params)) {
1338 SLOGE("kdf failed");
1339 return -1;
1340 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001341
1342 /* Initialize the decryption engine */
1343 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1344 return -1;
1345 }
1346 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1347 /* Decrypt the master key */
1348 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1349 encrypted_master_key, KEY_LEN_BYTES)) {
1350 return -1;
1351 }
1352 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1353 return -1;
1354 }
1355
1356 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1357 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001358 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001359
1360 /* Copy intermediate key if needed by params */
1361 if (intermediate_key && intermediate_key_size) {
1362 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1363 if (intermediate_key) {
1364 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1365 *intermediate_key_size = KEY_LEN_BYTES;
1366 }
1367 }
1368
1369 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001370}
1371
Kenny Rootc4c70f12013-06-14 12:11:38 -07001372static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001373{
Shawn Willden47ba10d2014-09-03 17:07:06 -06001374 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER_IMPROPER || ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001375 *kdf = scrypt_keymaster;
1376 *kdf_params = ftr;
1377 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001378 *kdf = scrypt;
1379 *kdf_params = ftr;
1380 } else {
1381 *kdf = pbkdf2;
1382 *kdf_params = NULL;
1383 }
1384}
1385
JP Abgrall7bdfa522013-11-15 13:42:56 -08001386static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001387 struct crypt_mnt_ftr *crypt_ftr,
1388 unsigned char** intermediate_key,
1389 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001390{
1391 kdf_func kdf;
1392 void *kdf_params;
1393 int ret;
1394
1395 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001396 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1397 decrypted_master_key, kdf, kdf_params,
1398 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001399 if (ret != 0) {
1400 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001401 }
1402
1403 return ret;
1404}
1405
1406static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1407 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001408 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001409 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001410 EVP_CIPHER_CTX e_ctx;
1411 int encrypted_len, final_len;
1412
1413 /* Get some random bits for a key */
1414 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001415 read(fd, key_buf, sizeof(key_buf));
1416 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001417 close(fd);
1418
1419 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001420 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001421}
1422
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001423static int wait_and_unmount(char *mountpoint)
1424{
1425 int i, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001426#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001427
1428 /* Now umount the tmpfs filesystem */
1429 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
1430 if (umount(mountpoint)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001431 if (errno == EINVAL) {
1432 /* EINVAL is returned if the directory is not a mountpoint,
1433 * i.e. there is no filesystem mounted there. So just get out.
1434 */
1435 break;
1436 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001437 sleep(1);
1438 i++;
1439 } else {
1440 break;
1441 }
1442 }
1443
1444 if (i < WAIT_UNMOUNT_COUNT) {
1445 SLOGD("unmounting %s succeeded\n", mountpoint);
1446 rc = 0;
1447 } else {
1448 SLOGE("unmounting %s failed\n", mountpoint);
1449 rc = -1;
1450 }
1451
1452 return rc;
1453}
1454
Ken Sumrallc5872692013-05-14 15:26:31 -07001455#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001456static int prep_data_fs(void)
1457{
1458 int i;
1459
1460 /* Do the prep of the /data filesystem */
1461 property_set("vold.post_fs_data_done", "0");
1462 property_set("vold.decrypt", "trigger_post_fs_data");
1463 SLOGD("Just triggered post_fs_data\n");
1464
Ken Sumrallc5872692013-05-14 15:26:31 -07001465 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001466 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001467 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001468
1469 property_get("vold.post_fs_data_done", p, "0");
1470 if (*p == '1') {
1471 break;
1472 } else {
1473 usleep(250000);
1474 }
1475 }
1476 if (i == DATA_PREP_TIMEOUT) {
1477 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001478 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001479 return -1;
1480 } else {
1481 SLOGD("post_fs_data done\n");
1482 return 0;
1483 }
1484}
1485
Paul Lawrence74f29f12014-08-28 15:54:10 -07001486static void cryptfs_set_corrupt()
1487{
1488 // Mark the footer as bad
1489 struct crypt_mnt_ftr crypt_ftr;
1490 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1491 SLOGE("Failed to get crypto footer - panic");
1492 return;
1493 }
1494
1495 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1496 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1497 SLOGE("Failed to set crypto footer - panic");
1498 return;
1499 }
1500}
1501
1502static void cryptfs_trigger_restart_min_framework()
1503{
1504 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1505 SLOGE("Failed to mount tmpfs on data - panic");
1506 return;
1507 }
1508
1509 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1510 SLOGE("Failed to trigger post fs data - panic");
1511 return;
1512 }
1513
1514 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1515 SLOGE("Failed to trigger restart min framework - panic");
1516 return;
1517 }
1518}
1519
Paul Lawrencef4faa572014-01-29 13:31:03 -08001520static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001521{
1522 char fs_type[32];
1523 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001524 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001525 char fs_options[256];
1526 unsigned long mnt_flags;
1527 struct stat statbuf;
1528 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001529 static int restart_successful = 0;
1530
1531 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001532 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001533 SLOGE("Encrypted filesystem not validated, aborting");
1534 return -1;
1535 }
1536
1537 if (restart_successful) {
1538 SLOGE("System already restarted with encrypted disk, aborting");
1539 return -1;
1540 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001541
Paul Lawrencef4faa572014-01-29 13:31:03 -08001542 if (restart_main) {
1543 /* Here is where we shut down the framework. The init scripts
1544 * start all services in one of three classes: core, main or late_start.
1545 * On boot, we start core and main. Now, we stop main, but not core,
1546 * as core includes vold and a few other really important things that
1547 * we need to keep running. Once main has stopped, we should be able
1548 * to umount the tmpfs /data, then mount the encrypted /data.
1549 * We then restart the class main, and also the class late_start.
1550 * At the moment, I've only put a few things in late_start that I know
1551 * are not needed to bring up the framework, and that also cause problems
1552 * with unmounting the tmpfs /data, but I hope to add add more services
1553 * to the late_start class as we optimize this to decrease the delay
1554 * till the user is asked for the password to the filesystem.
1555 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001556
Paul Lawrencef4faa572014-01-29 13:31:03 -08001557 /* The init files are setup to stop the class main when vold.decrypt is
1558 * set to trigger_reset_main.
1559 */
1560 property_set("vold.decrypt", "trigger_reset_main");
1561 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001562
Paul Lawrencef4faa572014-01-29 13:31:03 -08001563 /* Ugh, shutting down the framework is not synchronous, so until it
1564 * can be fixed, this horrible hack will wait a moment for it all to
1565 * shut down before proceeding. Without it, some devices cannot
1566 * restart the graphics services.
1567 */
1568 sleep(2);
1569 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001570
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001571 /* Now that the framework is shutdown, we should be able to umount()
1572 * the tmpfs filesystem, and mount the real one.
1573 */
1574
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001575 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1576 if (strlen(crypto_blkdev) == 0) {
1577 SLOGE("fs_crypto_blkdev not set\n");
1578 return -1;
1579 }
1580
Ken Sumralle5032c42012-04-01 23:58:44 -07001581 if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001582 /* If ro.crypto.readonly is set to 1, mount the decrypted
1583 * filesystem readonly. This is used when /data is mounted by
1584 * recovery mode.
1585 */
1586 char ro_prop[PROPERTY_VALUE_MAX];
1587 property_get("ro.crypto.readonly", ro_prop, "");
1588 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1589 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1590 rec->flags |= MS_RDONLY;
1591 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001592
Ken Sumralle5032c42012-04-01 23:58:44 -07001593 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001594 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, 0)) {
1595 SLOGE("Failed to mount decrypted data");
1596 cryptfs_set_corrupt();
1597 cryptfs_trigger_restart_min_framework();
1598 SLOGI("Started framework to offer wipe");
1599 return -1;
1600 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001601
Ken Sumralle5032c42012-04-01 23:58:44 -07001602 property_set("vold.decrypt", "trigger_load_persist_props");
1603 /* Create necessary paths on /data */
1604 if (prep_data_fs()) {
1605 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001606 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001607
1608 /* startup service classes main and late_start */
1609 property_set("vold.decrypt", "trigger_restart_framework");
1610 SLOGD("Just triggered restart_framework\n");
1611
1612 /* Give it a few moments to get started */
1613 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001614 }
1615
Ken Sumrall0cc16632011-01-18 20:32:26 -08001616 if (rc == 0) {
1617 restart_successful = 1;
1618 }
1619
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001620 return rc;
1621}
1622
Paul Lawrencef4faa572014-01-29 13:31:03 -08001623int cryptfs_restart(void)
1624{
1625 /* Call internal implementation forcing a restart of main service group */
1626 return cryptfs_restart_internal(1);
1627}
1628
Mark Salyzyn3e971272014-01-21 13:27:04 -08001629static int do_crypto_complete(char *mount_point UNUSED)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001630{
1631 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001632 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001633 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001634
1635 property_get("ro.crypto.state", encrypted_state, "");
1636 if (strcmp(encrypted_state, "encrypted") ) {
1637 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001638 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001639 }
1640
Ken Sumrall160b4d62013-04-22 12:15:39 -07001641 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001642 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001643
Ken Sumralle1a45852011-12-14 21:24:27 -08001644 /*
1645 * Only report this error if key_loc is a file and it exists.
1646 * If the device was never encrypted, and /data is not mountable for
1647 * some reason, returning 1 should prevent the UI from presenting the
1648 * a "enter password" screen, or worse, a "press button to wipe the
1649 * device" screen.
1650 */
1651 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1652 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001653 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001654 } else {
1655 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001656 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001657 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001658 }
1659
Paul Lawrence74f29f12014-08-28 15:54:10 -07001660 // Test for possible error flags
1661 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1662 SLOGE("Encryption process is partway completed\n");
1663 return CRYPTO_COMPLETE_PARTIAL;
1664 }
1665
1666 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1667 SLOGE("Encryption process was interrupted but cannot continue\n");
1668 return CRYPTO_COMPLETE_INCONSISTENT;
1669 }
1670
1671 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1672 SLOGE("Encryption is successful but data is corrupt\n");
1673 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001674 }
1675
1676 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001677 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001678}
1679
Paul Lawrencef4faa572014-01-29 13:31:03 -08001680static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1681 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001682{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001683 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001684 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001685 char crypto_blkdev[MAXPATHLEN];
1686 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001687 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001688 unsigned int orig_failed_decrypt_count;
1689 int rc;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001690 kdf_func kdf;
1691 void *kdf_params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001692 int use_keymaster = 0;
1693 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001694 unsigned char* intermediate_key = 0;
1695 size_t intermediate_key_size = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001696
Paul Lawrencef4faa572014-01-29 13:31:03 -08001697 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1698 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001699
Paul Lawrencef4faa572014-01-29 13:31:03 -08001700 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001701 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1702 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001703 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001704 rc = -1;
1705 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001706 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001707 }
1708
Paul Lawrencef4faa572014-01-29 13:31:03 -08001709 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1710
Paul Lawrence74f29f12014-08-28 15:54:10 -07001711 // Create crypto block device - all (non fatal) code paths
1712 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001713 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1714 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001715 SLOGE("Error creating decrypted block device\n");
1716 rc = -1;
1717 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001718 }
1719
Paul Lawrence74f29f12014-08-28 15:54:10 -07001720 /* Work out if the problem is the password or the data */
1721 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1722 scrypted_intermediate_key)];
1723 int N = 1 << crypt_ftr->N_factor;
1724 int r = 1 << crypt_ftr->r_factor;
1725 int p = 1 << crypt_ftr->p_factor;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001726
Paul Lawrence74f29f12014-08-28 15:54:10 -07001727 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1728 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1729 N, r, p, scrypted_intermediate_key,
1730 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001731
Paul Lawrence74f29f12014-08-28 15:54:10 -07001732 // Does the key match the crypto footer?
1733 if (rc == 0 && memcmp(scrypted_intermediate_key,
1734 crypt_ftr->scrypted_intermediate_key,
1735 sizeof(scrypted_intermediate_key)) == 0) {
1736 SLOGI("Password matches");
1737 rc = 0;
1738 } else {
1739 /* Try mounting the file system anyway, just in case the problem's with
1740 * the footer, not the key. */
1741 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1742 mkdir(tmp_mount_point, 0755);
1743 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1744 SLOGE("Error temp mounting decrypted block device\n");
1745 delete_crypto_blk_dev(label);
1746
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001747 rc = ++crypt_ftr->failed_decrypt_count;
1748 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001749 } else {
1750 /* Success! */
1751 SLOGI("Password did not match but decrypted drive mounted - continue");
1752 umount(tmp_mount_point);
1753 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001754 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001755 }
1756
1757 if (rc == 0) {
1758 crypt_ftr->failed_decrypt_count = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001759
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001760 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001761 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001762 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001763
1764 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001765 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001766 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001767 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001768 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001769 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001770 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001771
Paul Lawrence74f29f12014-08-28 15:54:10 -07001772 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001773 use_keymaster = keymaster_check_compatibility();
1774 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001775 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001776 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1777 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1778 upgrade = 1;
1779 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001780 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001781 upgrade = 1;
1782 }
1783
1784 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001785 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1786 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001787 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001788 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001789 }
1790 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1791 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001792 }
1793
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001794 errout:
1795 if (intermediate_key) {
1796 memset(intermediate_key, 0, intermediate_key_size);
1797 free(intermediate_key);
1798 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001799 return rc;
1800}
1801
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001802/* Called by vold when it wants to undo the crypto mapping of a volume it
1803 * manages. This is usually in response to a factory reset, when we want
1804 * to undo the crypto mapping so the volume is formatted in the clear.
1805 */
1806int cryptfs_revert_volume(const char *label)
1807{
1808 return delete_crypto_blk_dev((char *)label);
1809}
1810
Ken Sumrall29d8da82011-05-18 17:20:07 -07001811/*
1812 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1813 * Setup a dm-crypt mapping, use the saved master key from
1814 * setting up the /data mapping, and return the new device path.
1815 */
1816int cryptfs_setup_volume(const char *label, int major, int minor,
1817 char *crypto_sys_path, unsigned int max_path,
1818 int *new_major, int *new_minor)
1819{
1820 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1821 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001822 struct stat statbuf;
1823 int nr_sec, fd;
1824
1825 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1826
Ken Sumrall160b4d62013-04-22 12:15:39 -07001827 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001828
1829 /* Update the fs_size field to be the size of the volume */
1830 fd = open(real_blkdev, O_RDONLY);
1831 nr_sec = get_blkdev_size(fd);
1832 close(fd);
1833 if (nr_sec == 0) {
1834 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1835 return -1;
1836 }
1837
1838 sd_crypt_ftr.fs_size = nr_sec;
1839 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1840 crypto_blkdev, label);
1841
1842 stat(crypto_blkdev, &statbuf);
1843 *new_major = MAJOR(statbuf.st_rdev);
1844 *new_minor = MINOR(statbuf.st_rdev);
1845
1846 /* Create path to sys entry for this block device */
1847 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1848
1849 return 0;
1850}
1851
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001852int cryptfs_crypto_complete(void)
1853{
1854 return do_crypto_complete("/data");
1855}
1856
Paul Lawrencef4faa572014-01-29 13:31:03 -08001857int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1858{
1859 char encrypted_state[PROPERTY_VALUE_MAX];
1860 property_get("ro.crypto.state", encrypted_state, "");
1861 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1862 SLOGE("encrypted fs already validated or not running with encryption,"
1863 " aborting");
1864 return -1;
1865 }
1866
1867 if (get_crypt_ftr_and_key(crypt_ftr)) {
1868 SLOGE("Error getting crypt footer and key");
1869 return -1;
1870 }
1871
1872 return 0;
1873}
1874
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001875int cryptfs_check_passwd(char *passwd)
1876{
Paul Lawrencef4faa572014-01-29 13:31:03 -08001877 struct crypt_mnt_ftr crypt_ftr;
1878 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001879
Paul Lawrencef4faa572014-01-29 13:31:03 -08001880 rc = check_unmounted_and_get_ftr(&crypt_ftr);
1881 if (rc)
1882 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001883
Paul Lawrencef4faa572014-01-29 13:31:03 -08001884 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
1885 DATA_MNT_POINT, "userdata");
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001886
1887 if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001888 cryptfs_clear_password();
1889 password = strdup(passwd);
1890 struct timespec now;
1891 clock_gettime(CLOCK_BOOTTIME, &now);
1892 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001893 }
1894
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001895 return rc;
1896}
1897
Ken Sumrall3ad90722011-10-04 20:38:29 -07001898int cryptfs_verify_passwd(char *passwd)
1899{
1900 struct crypt_mnt_ftr crypt_ftr;
1901 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001902 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001903 char encrypted_state[PROPERTY_VALUE_MAX];
1904 int rc;
1905
1906 property_get("ro.crypto.state", encrypted_state, "");
1907 if (strcmp(encrypted_state, "encrypted") ) {
1908 SLOGE("device not encrypted, aborting");
1909 return -2;
1910 }
1911
1912 if (!master_key_saved) {
1913 SLOGE("encrypted fs not yet mounted, aborting");
1914 return -1;
1915 }
1916
1917 if (!saved_mount_point) {
1918 SLOGE("encrypted fs failed to save mount point, aborting");
1919 return -1;
1920 }
1921
Ken Sumrall160b4d62013-04-22 12:15:39 -07001922 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001923 SLOGE("Error getting crypt footer and key\n");
1924 return -1;
1925 }
1926
1927 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1928 /* If the device has no password, then just say the password is valid */
1929 rc = 0;
1930 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001931 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001932 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1933 /* They match, the password is correct */
1934 rc = 0;
1935 } else {
1936 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1937 sleep(1);
1938 rc = 1;
1939 }
1940 }
1941
1942 return rc;
1943}
1944
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001945/* Initialize a crypt_mnt_ftr structure. The keysize is
1946 * defaulted to 16 bytes, and the filesystem size to 0.
1947 * Presumably, at a minimum, the caller will update the
1948 * filesystem size and crypto_type_name after calling this function.
1949 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001950static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001951{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001952 off64_t off;
1953
1954 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001955 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001956 ftr->major_version = CURRENT_MAJOR_VERSION;
1957 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001958 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001959 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001960
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001961 switch (keymaster_check_compatibility()) {
1962 case 1:
1963 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1964 break;
1965
1966 case 0:
1967 ftr->kdf_type = KDF_SCRYPT;
1968 break;
1969
1970 default:
1971 SLOGE("keymaster_check_compatibility failed");
1972 return -1;
1973 }
1974
Kenny Rootc4c70f12013-06-14 12:11:38 -07001975 get_device_scrypt_params(ftr);
1976
Ken Sumrall160b4d62013-04-22 12:15:39 -07001977 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1978 if (get_crypt_ftr_info(NULL, &off) == 0) {
1979 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1980 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1981 ftr->persist_data_size;
1982 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001983
1984 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001985}
1986
Ken Sumrall29d8da82011-05-18 17:20:07 -07001987static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001988{
Ken Sumralle550f782013-08-20 13:48:23 -07001989 const char *args[10];
1990 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1991 int num_args;
1992 int status;
1993 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001994 int rc = -1;
1995
Ken Sumrall29d8da82011-05-18 17:20:07 -07001996 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001997 args[0] = "/system/bin/make_ext4fs";
1998 args[1] = "-a";
1999 args[2] = "/data";
2000 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07002001 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07002002 args[4] = size_str;
2003 args[5] = crypto_blkdev;
2004 num_args = 6;
2005 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
2006 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07002007 } else if (type == F2FS_FS) {
2008 args[0] = "/system/bin/mkfs.f2fs";
2009 args[1] = "-t";
2010 args[2] = "-d1";
2011 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07002012 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07002013 args[4] = size_str;
2014 num_args = 5;
2015 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
2016 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002017 } else {
2018 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
2019 return -1;
2020 }
2021
Ken Sumralle550f782013-08-20 13:48:23 -07002022 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
2023
2024 if (tmp != 0) {
2025 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002026 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07002027 if (WIFEXITED(status)) {
2028 if (WEXITSTATUS(status)) {
2029 SLOGE("Error creating filesystem on %s, exit status %d ",
2030 crypto_blkdev, WEXITSTATUS(status));
2031 } else {
2032 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
2033 rc = 0;
2034 }
2035 } else {
2036 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
2037 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002038 }
2039
2040 return rc;
2041}
2042
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002043#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08002044#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
2045#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002046
2047/* aligned 32K writes tends to make flash happy.
2048 * SD card association recommends it.
2049 */
2050#define BLOCKS_AT_A_TIME 8
2051
2052struct encryptGroupsData
2053{
2054 int realfd;
2055 int cryptofd;
2056 off64_t numblocks;
2057 off64_t one_pct, cur_pct, new_pct;
2058 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002059 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002060 char* real_blkdev, * crypto_blkdev;
2061 int count;
2062 off64_t offset;
2063 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08002064 off64_t last_written_sector;
2065 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002066 time_t time_started;
2067 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002068};
2069
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002070static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002071{
2072 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002073
2074 if (is_used) {
2075 data->used_blocks_already_done++;
2076 }
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002077 if (data->tot_used_blocks) {
2078 data->new_pct = data->used_blocks_already_done / data->one_pct;
2079 } else {
2080 data->new_pct = data->blocks_already_done / data->one_pct;
2081 }
2082
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002083 if (data->new_pct > data->cur_pct) {
2084 char buf[8];
2085 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07002086 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002087 property_set("vold.encrypt_progress", buf);
Elliott Hughescb33f572014-06-25 18:25:11 -07002088 SLOGI("Encrypted %" PRId64 " percent of drive", data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002089 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002090
2091 if (data->cur_pct >= 5) {
2092 double elapsed_time = difftime(time(NULL), data->time_started);
2093 off64_t remaining_blocks = data->tot_used_blocks
2094 - data->used_blocks_already_done;
2095 int remaining_time = (int)(elapsed_time * remaining_blocks
2096 / data->used_blocks_already_done);
Paul Lawrence71577502014-08-13 14:55:55 -07002097
2098 // Change time only if not yet set, lower, or a lot higher for
2099 // best user experience
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002100 if (data->remaining_time == -1
Paul Lawrence71577502014-08-13 14:55:55 -07002101 || remaining_time < data->remaining_time
2102 || remaining_time > data->remaining_time + 60) {
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002103 char buf[8];
2104 snprintf(buf, sizeof(buf), "%d", remaining_time);
2105 property_set("vold.encrypt_time_remaining", buf);
2106
Elliott Hughescb33f572014-06-25 18:25:11 -07002107 SLOGI("Encrypted %" PRId64 " percent of drive, %d seconds to go",
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002108 data->cur_pct, remaining_time);
2109 data->remaining_time = remaining_time;
2110 }
2111 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002112}
2113
2114static int flush_outstanding_data(struct encryptGroupsData* data)
2115{
2116 if (data->count == 0) {
2117 return 0;
2118 }
2119
Elliott Hughes231bdba2014-06-25 18:36:19 -07002120 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002121
2122 if (pread64(data->realfd, data->buffer,
2123 info.block_size * data->count, data->offset)
2124 <= 0) {
2125 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2126 data->real_blkdev);
2127 return -1;
2128 }
2129
2130 if (pwrite64(data->cryptofd, data->buffer,
2131 info.block_size * data->count, data->offset)
2132 <= 0) {
2133 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2134 data->crypto_blkdev);
2135 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002136 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002137 SLOGI("Encrypted %d blocks at sector %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002138 data->count, data->offset / info.block_size * CRYPT_SECTOR_SIZE);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002139 }
2140
2141 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002142 data->last_written_sector = (data->offset + data->count)
2143 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002144 return 0;
2145}
2146
2147static int encrypt_groups(struct encryptGroupsData* data)
2148{
2149 unsigned int i;
2150 u8 *block_bitmap = 0;
2151 unsigned int block;
2152 off64_t ret;
2153 int rc = -1;
2154
2155 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
2156 if (!data->buffer) {
2157 SLOGE("Failed to allocate crypto buffer");
2158 goto errout;
2159 }
2160
2161 block_bitmap = malloc(info.block_size);
2162 if (!block_bitmap) {
2163 SLOGE("failed to allocate block bitmap");
2164 goto errout;
2165 }
2166
2167 for (i = 0; i < aux_info.groups; ++i) {
2168 SLOGI("Encrypting group %d", i);
2169
2170 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2171 u32 block_count = min(info.blocks_per_group,
2172 aux_info.len_blocks - first_block);
2173
2174 off64_t offset = (u64)info.block_size
2175 * aux_info.bg_desc[i].bg_block_bitmap;
2176
2177 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2178 if (ret != (int)info.block_size) {
2179 SLOGE("failed to read all of block group bitmap %d", i);
2180 goto errout;
2181 }
2182
2183 offset = (u64)info.block_size * first_block;
2184
2185 data->count = 0;
2186
2187 for (block = 0; block < block_count; block++) {
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002188 int used = bitmap_get_bit(block_bitmap, block);
2189 update_progress(data, used);
2190 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002191 if (data->count == 0) {
2192 data->offset = offset;
2193 }
2194 data->count++;
2195 } else {
2196 if (flush_outstanding_data(data)) {
2197 goto errout;
2198 }
2199 }
2200
2201 offset += info.block_size;
2202
2203 /* Write data if we are aligned or buffer size reached */
2204 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2205 || data->count == BLOCKS_AT_A_TIME) {
2206 if (flush_outstanding_data(data)) {
2207 goto errout;
2208 }
2209 }
Paul Lawrence87999172014-02-20 12:21:31 -08002210
Paul Lawrence73d7a022014-06-09 14:10:09 -07002211 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002212 SLOGE("Stopping encryption due to low battery");
2213 rc = 0;
2214 goto errout;
2215 }
2216
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002217 }
2218 if (flush_outstanding_data(data)) {
2219 goto errout;
2220 }
2221 }
2222
Paul Lawrence87999172014-02-20 12:21:31 -08002223 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002224 rc = 0;
2225
2226errout:
2227 free(data->buffer);
2228 free(block_bitmap);
2229 return rc;
2230}
2231
2232static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2233 char *real_blkdev,
2234 off64_t size,
2235 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002236 off64_t tot_size,
2237 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002238{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002239 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002240 struct encryptGroupsData data;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002241 int rc; // Can't initialize without causing warning -Wclobbered
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002242
Paul Lawrence87999172014-02-20 12:21:31 -08002243 if (previously_encrypted_upto > *size_already_done) {
2244 SLOGD("Not fast encrypting since resuming part way through");
2245 return -1;
2246 }
2247
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002248 memset(&data, 0, sizeof(data));
2249 data.real_blkdev = real_blkdev;
2250 data.crypto_blkdev = crypto_blkdev;
2251
2252 if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
2253 SLOGE("Error opening real_blkdev %s for inplace encrypt\n",
2254 real_blkdev);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002255 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002256 goto errout;
2257 }
2258
2259 if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
2260 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n",
2261 crypto_blkdev);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002262 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002263 goto errout;
2264 }
2265
2266 if (setjmp(setjmp_env)) {
2267 SLOGE("Reading extent caused an exception");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002268 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002269 goto errout;
2270 }
2271
2272 if (read_ext(data.realfd, 0) != 0) {
2273 SLOGE("Failed to read extent");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002274 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002275 goto errout;
2276 }
2277
2278 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2279 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2280 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2281
2282 SLOGI("Encrypting filesystem in place...");
2283
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002284 data.tot_used_blocks = data.numblocks;
2285 for (i = 0; i < aux_info.groups; ++i) {
2286 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2287 }
2288
2289 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002290 data.cur_pct = 0;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002291 data.time_started = time(NULL);
2292 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002293
2294 rc = encrypt_groups(&data);
2295 if (rc) {
2296 SLOGE("Error encrypting groups");
2297 goto errout;
2298 }
2299
Paul Lawrence87999172014-02-20 12:21:31 -08002300 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002301 rc = 0;
2302
2303errout:
2304 close(data.realfd);
2305 close(data.cryptofd);
2306
2307 return rc;
2308}
2309
Daniel Rosenberge82df162014-08-15 22:19:23 +00002310static int encrypt_one_block_f2fs(u64 pos, void *data)
2311{
2312 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2313
2314 priv_dat->blocks_already_done = pos - 1;
2315 update_progress(priv_dat, 1);
2316
2317 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2318
2319 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
2320 SLOGE("Error reading real_blkdev %s for inplace encrypt", priv_dat->crypto_blkdev);
2321 return -1;
2322 }
2323
2324 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
2325 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", priv_dat->crypto_blkdev);
2326 return -1;
2327 } else {
2328 SLOGD("Encrypted block %"PRIu64, pos);
2329 }
2330
2331 return 0;
2332}
2333
2334static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2335 char *real_blkdev,
2336 off64_t size,
2337 off64_t *size_already_done,
2338 off64_t tot_size,
2339 off64_t previously_encrypted_upto)
2340{
2341 u32 i;
2342 struct encryptGroupsData data;
2343 struct f2fs_info *f2fs_info = NULL;
2344 int rc = -1;
2345 if (previously_encrypted_upto > *size_already_done) {
2346 SLOGD("Not fast encrypting since resuming part way through");
2347 return -1;
2348 }
2349 memset(&data, 0, sizeof(data));
2350 data.real_blkdev = real_blkdev;
2351 data.crypto_blkdev = crypto_blkdev;
2352 data.realfd = -1;
2353 data.cryptofd = -1;
2354 if ( (data.realfd = open64(real_blkdev, O_RDWR)) < 0) {
2355 SLOGE("Error opening real_blkdev %s for inplace encrypt\n",
2356 real_blkdev);
2357 goto errout;
2358 }
2359 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY)) < 0) {
2360 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n",
2361 crypto_blkdev);
2362 goto errout;
2363 }
2364
2365 f2fs_info = generate_f2fs_info(data.realfd);
2366 if (!f2fs_info)
2367 goto errout;
2368
2369 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2370 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2371 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2372
2373 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2374
2375 data.one_pct = data.tot_used_blocks / 100;
2376 data.cur_pct = 0;
2377 data.time_started = time(NULL);
2378 data.remaining_time = -1;
2379
2380 data.buffer = malloc(f2fs_info->block_size);
2381 if (!data.buffer) {
2382 SLOGE("Failed to allocate crypto buffer");
2383 goto errout;
2384 }
2385
2386 data.count = 0;
2387
2388 /* Currently, this either runs to completion, or hits a nonrecoverable error */
2389 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2390
2391 if (rc) {
2392 SLOGE("Error in running over blocks");
2393 goto errout;
2394 }
2395
2396 *size_already_done += size;
2397 rc = 0;
2398
2399errout:
2400 if (rc)
2401 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2402
2403 free(f2fs_info);
2404 free(data.buffer);
2405 close(data.realfd);
2406 close(data.cryptofd);
2407
2408 return rc;
2409}
2410
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002411static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2412 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002413 off64_t tot_size,
2414 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002415{
2416 int realfd, cryptofd;
2417 char *buf[CRYPT_INPLACE_BUFSIZE];
2418 int rc = -1;
2419 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002420 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002421 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002422
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002423 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
2424 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
2425 return -1;
2426 }
2427
2428 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
2429 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
2430 close(realfd);
2431 return -1;
2432 }
2433
2434 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2435 * The size passed in is the number of 512 byte sectors in the filesystem.
2436 * So compute the number of whole 4K blocks we should read/write,
2437 * and the remainder.
2438 */
2439 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2440 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002441 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2442 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002443
2444 SLOGE("Encrypting filesystem in place...");
2445
Paul Lawrence87999172014-02-20 12:21:31 -08002446 i = previously_encrypted_upto + 1 - *size_already_done;
2447
2448 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2449 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2450 goto errout;
2451 }
2452
2453 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2454 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2455 goto errout;
2456 }
2457
2458 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2459 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2460 SLOGE("Error reading initial sectors from real_blkdev %s for "
2461 "inplace encrypt\n", crypto_blkdev);
2462 goto errout;
2463 }
2464 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2465 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2466 "inplace encrypt\n", crypto_blkdev);
2467 goto errout;
2468 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002469 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002470 }
2471 }
2472
Ken Sumrall29d8da82011-05-18 17:20:07 -07002473 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002474 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002475 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002476 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002477 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002478 if (new_pct > cur_pct) {
2479 char buf[8];
2480
2481 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002482 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002483 property_set("vold.encrypt_progress", buf);
2484 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002485 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002486 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002487 goto errout;
2488 }
2489 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002490 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2491 goto errout;
2492 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002493 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002494 CRYPT_SECTORS_PER_BUFSIZE,
2495 i * CRYPT_SECTORS_PER_BUFSIZE);
2496 }
2497
Paul Lawrence73d7a022014-06-09 14:10:09 -07002498 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002499 SLOGE("Stopping encryption due to low battery");
2500 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2501 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002502 goto errout;
2503 }
2504 }
2505
2506 /* Do any remaining sectors */
2507 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002508 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2509 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002510 goto errout;
2511 }
Paul Lawrence87999172014-02-20 12:21:31 -08002512 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2513 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002514 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002515 } else {
2516 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002517 }
2518 }
2519
Ken Sumrall29d8da82011-05-18 17:20:07 -07002520 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002521 rc = 0;
2522
2523errout:
2524 close(realfd);
2525 close(cryptofd);
2526
2527 return rc;
2528}
2529
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002530static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2531 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002532 off64_t tot_size,
2533 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002534{
Paul Lawrence87999172014-02-20 12:21:31 -08002535 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002536 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002537 }
2538
2539 if (*size_already_done + size < previously_encrypted_upto) {
2540 *size_already_done += size;
2541 return 0;
2542 }
2543
Daniel Rosenberge82df162014-08-15 22:19:23 +00002544 /* TODO: identify filesystem type.
2545 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2546 * then we will drop down to cryptfs_enable_inplace_f2fs.
2547 * */
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002548 if (cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002549 size, size_already_done,
2550 tot_size, previously_encrypted_upto) == 0) {
2551 return 0;
2552 }
2553
2554 if (cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
2555 size, size_already_done,
2556 tot_size, previously_encrypted_upto) == 0) {
2557 return 0;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002558 }
2559
2560 return cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002561 size, size_already_done, tot_size,
2562 previously_encrypted_upto);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002563}
2564
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002565#define CRYPTO_ENABLE_WIPE 1
2566#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002567
2568#define FRAMEWORK_BOOT_WAIT 60
2569
Ken Sumrall29d8da82011-05-18 17:20:07 -07002570static inline int should_encrypt(struct volume_info *volume)
2571{
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002572 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
Ken Sumrall29d8da82011-05-18 17:20:07 -07002573 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
2574}
2575
Paul Lawrence87999172014-02-20 12:21:31 -08002576static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2577{
2578 int fd = open(filename, O_RDONLY);
2579 if (fd == -1) {
2580 SLOGE("Error opening file %s", filename);
2581 return -1;
2582 }
2583
2584 char block[CRYPT_INPLACE_BUFSIZE];
2585 memset(block, 0, sizeof(block));
2586 if (unix_read(fd, block, sizeof(block)) < 0) {
2587 SLOGE("Error reading file %s", filename);
2588 close(fd);
2589 return -1;
2590 }
2591
2592 close(fd);
2593
2594 SHA256_CTX c;
2595 SHA256_Init(&c);
2596 SHA256_Update(&c, block, sizeof(block));
2597 SHA256_Final(buf, &c);
2598
2599 return 0;
2600}
2601
JP Abgrall62c7af32014-06-16 13:01:23 -07002602static int get_fs_type(struct fstab_rec *rec)
2603{
2604 if (!strcmp(rec->fs_type, "ext4")) {
2605 return EXT4_FS;
2606 } else if (!strcmp(rec->fs_type, "f2fs")) {
2607 return F2FS_FS;
2608 } else {
2609 return -1;
2610 }
2611}
2612
Paul Lawrence87999172014-02-20 12:21:31 -08002613static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2614 char *crypto_blkdev, char *real_blkdev,
2615 int previously_encrypted_upto)
2616{
2617 off64_t cur_encryption_done=0, tot_encryption_size=0;
2618 int i, rc = -1;
2619
Paul Lawrence73d7a022014-06-09 14:10:09 -07002620 if (!is_battery_ok_to_start()) {
2621 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002622 return 0;
2623 }
2624
2625 /* The size of the userdata partition, and add in the vold volumes below */
2626 tot_encryption_size = crypt_ftr->fs_size;
2627
2628 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002629 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2630 int fs_type = get_fs_type(rec);
2631 if (fs_type < 0) {
2632 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2633 return -1;
2634 }
2635 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002636 } else if (how == CRYPTO_ENABLE_INPLACE) {
2637 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2638 crypt_ftr->fs_size, &cur_encryption_done,
2639 tot_encryption_size,
2640 previously_encrypted_upto);
2641
Paul Lawrence73d7a022014-06-09 14:10:09 -07002642 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002643 crypt_ftr->encrypted_upto = cur_encryption_done;
2644 }
2645
Paul Lawrence73d7a022014-06-09 14:10:09 -07002646 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002647 /* The inplace routine never actually sets the progress to 100% due
2648 * to the round down nature of integer division, so set it here */
2649 property_set("vold.encrypt_progress", "100");
2650 }
2651 } else {
2652 /* Shouldn't happen */
2653 SLOGE("cryptfs_enable: internal error, unknown option\n");
2654 rc = -1;
2655 }
2656
2657 return rc;
2658}
2659
Paul Lawrence13486032014-02-03 13:28:11 -08002660int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
2661 int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002662{
2663 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002664 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07002665 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002666 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07002667 int rc=-1, fd, i, ret;
Paul Lawrence87999172014-02-20 12:21:31 -08002668 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002669 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002670 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002671 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002672 char key_loc[PROPERTY_VALUE_MAX];
2673 char fuse_sdcard[PROPERTY_VALUE_MAX];
2674 char *sd_mnt_point;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002675 int num_vols;
2676 struct volume_info *vol_list = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002677 off64_t previously_encrypted_upto = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002678
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002679 if (!strcmp(howarg, "wipe")) {
2680 how = CRYPTO_ENABLE_WIPE;
2681 } else if (! strcmp(howarg, "inplace")) {
2682 how = CRYPTO_ENABLE_INPLACE;
2683 } else {
2684 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002685 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002686 }
2687
Paul Lawrence87999172014-02-20 12:21:31 -08002688 /* See if an encryption was underway and interrupted */
2689 if (how == CRYPTO_ENABLE_INPLACE
2690 && get_crypt_ftr_and_key(&crypt_ftr) == 0
2691 && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
2692 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2693 crypt_ftr.encrypted_upto = 0;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002694 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
2695
2696 /* At this point, we are in an inconsistent state. Until we successfully
2697 complete encryption, a reboot will leave us broken. So mark the
2698 encryption failed in case that happens.
2699 On successfully completing encryption, remove this flag */
2700 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2701
2702 put_crypt_ftr_and_key(&crypt_ftr);
Paul Lawrence87999172014-02-20 12:21:31 -08002703 }
2704
2705 property_get("ro.crypto.state", encrypted_state, "");
2706 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2707 SLOGE("Device is already running encrypted, aborting");
2708 goto error_unencrypted;
2709 }
2710
2711 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2712 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002713 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002714
Ken Sumrall3ed82362011-01-28 23:31:16 -08002715 /* Get the size of the real block device */
2716 fd = open(real_blkdev, O_RDONLY);
2717 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
2718 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2719 goto error_unencrypted;
2720 }
2721 close(fd);
2722
2723 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002724 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002725 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002726 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002727 if (fs_size_sec == 0)
2728 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2729
Paul Lawrence87999172014-02-20 12:21:31 -08002730 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002731
2732 if (fs_size_sec > max_fs_size_sec) {
2733 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2734 goto error_unencrypted;
2735 }
2736 }
2737
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002738 /* Get a wakelock as this may take a while, and we don't want the
2739 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2740 * wants to keep the screen on, it can grab a full wakelock.
2741 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002742 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002743 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2744
Jeff Sharkey7382f812012-08-23 14:08:59 -07002745 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07002746 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07002747 if (!sd_mnt_point) {
2748 sd_mnt_point = getenv("EXTERNAL_STORAGE");
2749 }
2750 if (!sd_mnt_point) {
2751 sd_mnt_point = "/mnt/sdcard";
2752 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07002753
Paul Lawrence87999172014-02-20 12:21:31 -08002754 /* TODO
2755 * Currently do not have test devices with multiple encryptable volumes.
2756 * When we acquire some, re-add support.
2757 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002758 num_vols=vold_getNumDirectVolumes();
2759 vol_list = malloc(sizeof(struct volume_info) * num_vols);
2760 vold_getDirectVolumeList(vol_list);
2761
2762 for (i=0; i<num_vols; i++) {
2763 if (should_encrypt(&vol_list[i])) {
Paul Lawrence87999172014-02-20 12:21:31 -08002764 SLOGE("Cannot encrypt if there are multiple encryptable volumes"
2765 "%s\n", vol_list[i].label);
2766 goto error_unencrypted;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002767 }
2768 }
2769
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002770 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002771 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002772 */
2773 property_set("vold.decrypt", "trigger_shutdown_framework");
2774 SLOGD("Just asked init to shut down class main\n");
2775
Ken Sumrall425524d2012-06-14 20:55:28 -07002776 if (vold_unmountAllAsecs()) {
2777 /* Just report the error. If any are left mounted,
2778 * umounting /data below will fail and handle the error.
2779 */
2780 SLOGE("Error unmounting internal asecs");
2781 }
2782
Ken Sumrall29d8da82011-05-18 17:20:07 -07002783 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
2784 if (!strcmp(fuse_sdcard, "true")) {
2785 /* This is a device using the fuse layer to emulate the sdcard semantics
2786 * on top of the userdata partition. vold does not manage it, it is managed
2787 * by the sdcard service. The sdcard service was killed by the property trigger
2788 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
2789 * unlike the case for vold managed devices above.
2790 */
2791 if (wait_and_unmount(sd_mnt_point)) {
2792 goto error_shutting_down;
2793 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002794 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002795
2796 /* Now unmount the /data partition. */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002797 if (wait_and_unmount(DATA_MNT_POINT)) {
JP Abgrall502dc742013-11-01 13:06:20 -07002798 if (allow_reboot) {
2799 goto error_shutting_down;
2800 } else {
2801 goto error_unencrypted;
2802 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002803 }
2804
2805 /* Do extra work for a better UX when doing the long inplace encryption */
2806 if (how == CRYPTO_ENABLE_INPLACE) {
2807 /* Now that /data is unmounted, we need to mount a tmpfs
2808 * /data, set a property saying we're doing inplace encryption,
2809 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002810 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002811 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002812 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002813 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002814 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002815 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002816
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002817 /* restart the framework. */
2818 /* Create necessary paths on /data */
2819 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002820 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002821 }
2822
Ken Sumrall92736ef2012-10-17 20:57:14 -07002823 /* Ugh, shutting down the framework is not synchronous, so until it
2824 * can be fixed, this horrible hack will wait a moment for it all to
2825 * shut down before proceeding. Without it, some devices cannot
2826 * restart the graphics services.
2827 */
2828 sleep(2);
2829
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002830 /* startup service classes main and late_start */
2831 property_set("vold.decrypt", "trigger_restart_min_framework");
2832 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002833
Ken Sumrall7df84122011-01-18 14:04:08 -08002834 /* OK, the framework is restarted and will soon be showing a
2835 * progress bar. Time to setup an encrypted mapping, and
2836 * either write a new filesystem, or encrypt in place updating
2837 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002838 */
2839 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002840
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002841 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002842 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence87999172014-02-20 12:21:31 -08002843 if (previously_encrypted_upto == 0) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002844 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2845 goto error_shutting_down;
2846 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002847
Paul Lawrence87999172014-02-20 12:21:31 -08002848 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2849 crypt_ftr.fs_size = nr_sec
2850 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2851 } else {
2852 crypt_ftr.fs_size = nr_sec;
2853 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002854 /* At this point, we are in an inconsistent state. Until we successfully
2855 complete encryption, a reboot will leave us broken. So mark the
2856 encryption failed in case that happens.
2857 On successfully completing encryption, remove this flag */
2858 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence87999172014-02-20 12:21:31 -08002859 crypt_ftr.crypt_type = crypt_type;
2860 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002861
Paul Lawrence87999172014-02-20 12:21:31 -08002862 /* Make an encrypted master key */
2863 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
2864 SLOGE("Cannot create encrypted master key\n");
2865 goto error_shutting_down;
2866 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002867
Paul Lawrence87999172014-02-20 12:21:31 -08002868 /* Write the key to the end of the partition */
2869 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002870
Paul Lawrence87999172014-02-20 12:21:31 -08002871 /* If any persistent data has been remembered, save it.
2872 * If none, create a valid empty table and save that.
2873 */
2874 if (!persist_data) {
2875 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
2876 if (pdata) {
2877 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2878 persist_data = pdata;
2879 }
2880 }
2881 if (persist_data) {
2882 save_persistent_data();
2883 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002884 }
2885
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002886 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002887 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
2888 "userdata");
2889
Paul Lawrence87999172014-02-20 12:21:31 -08002890 /* If we are continuing, check checksums match */
2891 rc = 0;
2892 if (previously_encrypted_upto) {
2893 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2894 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002895
Paul Lawrence87999172014-02-20 12:21:31 -08002896 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2897 sizeof(hash_first_block)) != 0) {
2898 SLOGE("Checksums do not match - trigger wipe");
2899 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002900 }
2901 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002902
Paul Lawrence87999172014-02-20 12:21:31 -08002903 if (!rc) {
2904 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
2905 crypto_blkdev, real_blkdev,
2906 previously_encrypted_upto);
2907 }
2908
2909 /* Calculate checksum if we are not finished */
Paul Lawrence73d7a022014-06-09 14:10:09 -07002910 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002911 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2912 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002913 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002914 SLOGE("Error calculating checksum for continuing encryption");
2915 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002916 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002917 }
2918
2919 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002920 delete_crypto_blk_dev("userdata");
Ken Sumrall29d8da82011-05-18 17:20:07 -07002921
2922 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002923
2924 if (! rc) {
2925 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002926 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002927
Paul Lawrence6bfed202014-07-28 12:47:22 -07002928 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002929 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2930 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002931 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002932 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002933
Paul Lawrence6bfed202014-07-28 12:47:22 -07002934 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002935
Paul Lawrence73d7a022014-06-09 14:10:09 -07002936 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002937 char value[PROPERTY_VALUE_MAX];
2938 property_get("ro.crypto.state", value, "");
2939 if (!strcmp(value, "")) {
2940 /* default encryption - continue first boot sequence */
2941 property_set("ro.crypto.state", "encrypted");
2942 release_wake_lock(lockid);
2943 cryptfs_check_passwd(DEFAULT_PASSWORD);
2944 cryptfs_restart_internal(1);
2945 return 0;
2946 } else {
2947 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08002948 cryptfs_reboot(reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002949 }
Paul Lawrence87999172014-02-20 12:21:31 -08002950 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002951 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Paul Lawrence87999172014-02-20 12:21:31 -08002952 cryptfs_reboot(shutdown);
2953 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002954 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002955 char value[PROPERTY_VALUE_MAX];
2956
Ken Sumrall319369a2012-06-27 16:30:18 -07002957 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002958 if (!strcmp(value, "1")) {
2959 /* wipe data if encryption failed */
2960 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
2961 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07002962 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002963 if (fd >= 0) {
2964 write(fd, "--wipe_data", strlen("--wipe_data") + 1);
2965 close(fd);
2966 } else {
2967 SLOGE("could not open /cache/recovery/command\n");
2968 }
Paul Lawrence87999172014-02-20 12:21:31 -08002969 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002970 } else {
2971 /* set property to trigger dialog */
2972 property_set("vold.encrypt_progress", "error_partially_encrypted");
2973 release_wake_lock(lockid);
2974 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002975 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002976 }
2977
Ken Sumrall3ed82362011-01-28 23:31:16 -08002978 /* hrm, the encrypt step claims success, but the reboot failed.
2979 * This should not happen.
2980 * Set the property and return. Hope the framework can deal with it.
2981 */
2982 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002983 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002984 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002985
2986error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07002987 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002988 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002989 if (lockid[0]) {
2990 release_wake_lock(lockid);
2991 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002992 return -1;
2993
2994error_shutting_down:
2995 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2996 * but the framework is stopped and not restarted to show the error, so it's up to
2997 * vold to restart the system.
2998 */
2999 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08003000 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003001
3002 /* shouldn't get here */
3003 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003004 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003005 if (lockid[0]) {
3006 release_wake_lock(lockid);
3007 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003008 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003009}
3010
Paul Lawrence45f10532014-04-04 18:11:56 +00003011int cryptfs_enable(char *howarg, int type, char *passwd, int allow_reboot)
Paul Lawrence13486032014-02-03 13:28:11 -08003012{
Paul Lawrence45f10532014-04-04 18:11:56 +00003013 return cryptfs_enable_internal(howarg, type, passwd, allow_reboot);
Paul Lawrence13486032014-02-03 13:28:11 -08003014}
3015
3016int cryptfs_enable_default(char *howarg, int allow_reboot)
3017{
3018 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
3019 DEFAULT_PASSWORD, allow_reboot);
3020}
3021
3022int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003023{
3024 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003025 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003026
3027 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003028 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003029 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003030 return -1;
3031 }
3032
Paul Lawrencef4faa572014-01-29 13:31:03 -08003033 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3034 SLOGE("Invalid crypt_type %d", crypt_type);
3035 return -1;
3036 }
3037
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003038 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003039 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003040 SLOGE("Error getting crypt footer and key");
3041 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003042 }
3043
Paul Lawrencef4faa572014-01-29 13:31:03 -08003044 crypt_ftr.crypt_type = crypt_type;
3045
3046 encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
3047 : newpw,
3048 crypt_ftr.salt,
3049 saved_master_key,
3050 crypt_ftr.master_key,
3051 &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003052
Jason parks70a4b3f2011-01-28 10:10:47 -06003053 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003054 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003055
3056 return 0;
3057}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003058
3059static int persist_get_key(char *fieldname, char *value)
3060{
3061 unsigned int i;
3062
3063 if (persist_data == NULL) {
3064 return -1;
3065 }
3066 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3067 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3068 /* We found it! */
3069 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3070 return 0;
3071 }
3072 }
3073
3074 return -1;
3075}
3076
3077static int persist_set_key(char *fieldname, char *value, int encrypted)
3078{
3079 unsigned int i;
3080 unsigned int num;
3081 struct crypt_mnt_ftr crypt_ftr;
3082 unsigned int max_persistent_entries;
3083 unsigned int dsize;
3084
3085 if (persist_data == NULL) {
3086 return -1;
3087 }
3088
3089 /* If encrypted, use the values from the crypt_ftr, otherwise
3090 * use the values for the current spec.
3091 */
3092 if (encrypted) {
3093 if(get_crypt_ftr_and_key(&crypt_ftr)) {
3094 return -1;
3095 }
3096 dsize = crypt_ftr.persist_data_size;
3097 } else {
3098 dsize = CRYPT_PERSIST_DATA_SIZE;
3099 }
3100 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3101 sizeof(struct crypt_persist_entry);
3102
3103 num = persist_data->persist_valid_entries;
3104
3105 for (i = 0; i < num; i++) {
3106 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3107 /* We found an existing entry, update it! */
3108 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3109 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3110 return 0;
3111 }
3112 }
3113
3114 /* We didn't find it, add it to the end, if there is room */
3115 if (persist_data->persist_valid_entries < max_persistent_entries) {
3116 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3117 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3118 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3119 persist_data->persist_valid_entries++;
3120 return 0;
3121 }
3122
3123 return -1;
3124}
3125
3126/* Return the value of the specified field. */
3127int cryptfs_getfield(char *fieldname, char *value, int len)
3128{
3129 char temp_value[PROPERTY_VALUE_MAX];
3130 char real_blkdev[MAXPATHLEN];
3131 /* 0 is success, 1 is not encrypted,
3132 * -1 is value not set, -2 is any other error
3133 */
3134 int rc = -2;
3135
3136 if (persist_data == NULL) {
3137 load_persistent_data();
3138 if (persist_data == NULL) {
3139 SLOGE("Getfield error, cannot load persistent data");
3140 goto out;
3141 }
3142 }
3143
3144 if (!persist_get_key(fieldname, temp_value)) {
3145 /* We found it, copy it to the caller's buffer and return */
3146 strlcpy(value, temp_value, len);
3147 rc = 0;
3148 } else {
3149 /* Sadness, it's not there. Return the error */
3150 rc = -1;
3151 }
3152
3153out:
3154 return rc;
3155}
3156
3157/* Set the value of the specified field. */
3158int cryptfs_setfield(char *fieldname, char *value)
3159{
3160 struct crypt_persist_data stored_pdata;
3161 struct crypt_persist_data *pdata_p;
3162 struct crypt_mnt_ftr crypt_ftr;
3163 char encrypted_state[PROPERTY_VALUE_MAX];
3164 /* 0 is success, -1 is an error */
3165 int rc = -1;
3166 int encrypted = 0;
3167
3168 if (persist_data == NULL) {
3169 load_persistent_data();
3170 if (persist_data == NULL) {
3171 SLOGE("Setfield error, cannot load persistent data");
3172 goto out;
3173 }
3174 }
3175
3176 property_get("ro.crypto.state", encrypted_state, "");
3177 if (!strcmp(encrypted_state, "encrypted") ) {
3178 encrypted = 1;
3179 }
3180
3181 if (persist_set_key(fieldname, value, encrypted)) {
3182 goto out;
3183 }
3184
3185 /* If we are running encrypted, save the persistent data now */
3186 if (encrypted) {
3187 if (save_persistent_data()) {
3188 SLOGE("Setfield error, cannot save persistent data");
3189 goto out;
3190 }
3191 }
3192
3193 rc = 0;
3194
3195out:
3196 return rc;
3197}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003198
3199/* Checks userdata. Attempt to mount the volume if default-
3200 * encrypted.
3201 * On success trigger next init phase and return 0.
3202 * Currently do not handle failure - see TODO below.
3203 */
3204int cryptfs_mount_default_encrypted(void)
3205{
3206 char decrypt_state[PROPERTY_VALUE_MAX];
3207 property_get("vold.decrypt", decrypt_state, "0");
3208 if (!strcmp(decrypt_state, "0")) {
3209 SLOGE("Not encrypted - should not call here");
3210 } else {
3211 int crypt_type = cryptfs_get_password_type();
3212 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3213 SLOGE("Bad crypt type - error");
3214 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3215 SLOGD("Password is not default - "
3216 "starting min framework to prompt");
3217 property_set("vold.decrypt", "trigger_restart_min_framework");
3218 return 0;
3219 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3220 SLOGD("Password is default - restarting filesystem");
3221 cryptfs_restart_internal(0);
3222 return 0;
3223 } else {
3224 SLOGE("Encrypted, default crypt type but can't decrypt");
3225 }
3226 }
3227
Paul Lawrence6bfed202014-07-28 12:47:22 -07003228 /** Corrupt. Allow us to boot into framework, which will detect bad
3229 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003230 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003231 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003232 return 0;
3233}
3234
3235/* Returns type of the password, default, pattern, pin or password.
3236 */
3237int cryptfs_get_password_type(void)
3238{
3239 struct crypt_mnt_ftr crypt_ftr;
3240
3241 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3242 SLOGE("Error getting crypt footer and key\n");
3243 return -1;
3244 }
3245
Paul Lawrence6bfed202014-07-28 12:47:22 -07003246 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3247 return -1;
3248 }
3249
Paul Lawrencef4faa572014-01-29 13:31:03 -08003250 return crypt_ftr.crypt_type;
3251}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003252
Paul Lawrence399317e2014-03-10 13:20:50 -07003253char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003254{
Paul Lawrence399317e2014-03-10 13:20:50 -07003255 struct timespec now;
3256 clock_gettime(CLOCK_MONOTONIC, &now);
3257 if (now.tv_sec < password_expiry_time) {
3258 return password;
3259 } else {
3260 cryptfs_clear_password();
3261 return 0;
3262 }
3263}
3264
3265void cryptfs_clear_password()
3266{
3267 if (password) {
3268 size_t len = strlen(password);
3269 memset(password, 0, len);
3270 free(password);
3271 password = 0;
3272 password_expiry_time = 0;
3273 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003274}