blob: f6e6ebaa7c32e78a4280f7f3f054c0c2ece99536 [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 Willdene17a9c42014-09-08 13:04:08 -0600185/* This signs the given object using the keymaster key. */
186static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600187 const unsigned char *object,
188 const size_t object_size,
189 unsigned char **signature,
190 size_t *signature_size)
191{
192 int rc = 0;
193 keymaster_device_t *keymaster_dev = 0;
194 if (keymaster_init(&keymaster_dev)) {
195 SLOGE("Failed to init keymaster");
196 return -1;
197 }
198
199 /* We currently set the digest type to DIGEST_NONE because it's the
200 * only supported value for keymaster. A similar issue exists with
201 * PADDING_NONE. Long term both of these should likely change.
202 */
203 keymaster_rsa_sign_params_t params;
204 params.digest_type = DIGEST_NONE;
205 params.padding_type = PADDING_NONE;
206
207 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600208 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600209 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600210
Shawn Willdene17a9c42014-09-08 13:04:08 -0600211 // To sign a message with RSA, the message must satisfy two
212 // constraints:
213 //
214 // 1. The message, when interpreted as a big-endian numeric value, must
215 // be strictly less than the public modulus of the RSA key. Note
216 // that because the most significant bit of the public modulus is
217 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
218 // key), an n-bit message with most significant bit 0 always
219 // satisfies this requirement.
220 //
221 // 2. The message must have the same length in bits as the public
222 // modulus of the RSA key. This requirement isn't mathematically
223 // necessary, but is necessary to ensure consistency in
224 // implementations.
225 switch (ftr->kdf_type) {
226 case KDF_SCRYPT_KEYMASTER_UNPADDED:
227 // This is broken: It produces a message which is shorter than
228 // the public modulus, failing criterion 2.
229 memcpy(to_sign, object, object_size);
230 to_sign_size = object_size;
231 SLOGI("Signing unpadded object");
232 break;
233 case KDF_SCRYPT_KEYMASTER_BADLY_PADDED:
234 // This is broken: Since the value of object is uniformly
235 // distributed, it produces a message that is larger than the
236 // public modulus with probability 0.25.
237 memcpy(to_sign, object, min(RSA_KEY_SIZE_BYTES, object_size));
238 SLOGI("Signing end-padded object");
239 break;
240 case KDF_SCRYPT_KEYMASTER:
241 // This ensures the most significant byte of the signed message
242 // is zero. We could have zero-padded to the left instead, but
243 // this approach is slightly more robust against changes in
244 // object size. However, it's still broken (but not unusably
245 // so) because we really should be using a proper RSA padding
246 // function, such as OAEP.
247 //
248 // TODO(paullawrence): When keymaster 0.4 is available, change
249 // this to use the padding options it provides.
250 memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
251 SLOGI("Signing safely-padded object");
252 break;
253 default:
254 SLOGE("Unknown KDF type %d", ftr->kdf_type);
255 return -1;
256 }
257
Shawn Willden47ba10d2014-09-03 17:07:06 -0600258 rc = keymaster_dev->sign_data(keymaster_dev,
259 &params,
260 ftr->keymaster_blob,
261 ftr->keymaster_blob_size,
262 to_sign,
Shawn Willdene17a9c42014-09-08 13:04:08 -0600263 to_sign_size,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600264 signature,
265 signature_size);
266
267 keymaster_close(keymaster_dev);
268 return rc;
269}
270
Paul Lawrence399317e2014-03-10 13:20:50 -0700271/* Store password when userdata is successfully decrypted and mounted.
272 * Cleared by cryptfs_clear_password
273 *
274 * To avoid a double prompt at boot, we need to store the CryptKeeper
275 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
276 * Since the entire framework is torn down and rebuilt after encryption,
277 * we have to use a daemon or similar to store the password. Since vold
278 * is secured against IPC except from system processes, it seems a reasonable
279 * place to store this.
280 *
281 * password should be cleared once it has been used.
282 *
283 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800284 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700285static char* password = 0;
286static int password_expiry_time = 0;
287static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800288
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800289extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800290
Paul Lawrence87999172014-02-20 12:21:31 -0800291enum RebootType {reboot, recovery, shutdown};
292static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700293{
Paul Lawrence87999172014-02-20 12:21:31 -0800294 switch(rt) {
295 case reboot:
296 property_set(ANDROID_RB_PROPERTY, "reboot");
297 break;
298
299 case recovery:
300 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
301 break;
302
303 case shutdown:
304 property_set(ANDROID_RB_PROPERTY, "shutdown");
305 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700306 }
Paul Lawrence87999172014-02-20 12:21:31 -0800307
Ken Sumralladfba362013-06-04 16:37:52 -0700308 sleep(20);
309
310 /* Shouldn't get here, reboot should happen before sleep times out */
311 return;
312}
313
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800314static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
315{
316 memset(io, 0, dataSize);
317 io->data_size = dataSize;
318 io->data_start = sizeof(struct dm_ioctl);
319 io->version[0] = 4;
320 io->version[1] = 0;
321 io->version[2] = 0;
322 io->flags = flags;
323 if (name) {
324 strncpy(io->name, name, sizeof(io->name));
325 }
326}
327
Kenny Rootc4c70f12013-06-14 12:11:38 -0700328/**
329 * Gets the default device scrypt parameters for key derivation time tuning.
330 * The parameters should lead to about one second derivation time for the
331 * given device.
332 */
333static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
334 const int default_params[] = SCRYPT_DEFAULTS;
335 int params[] = SCRYPT_DEFAULTS;
336 char paramstr[PROPERTY_VALUE_MAX];
337 char *token;
338 char *saveptr;
339 int i;
340
341 property_get(SCRYPT_PROP, paramstr, "");
342 if (paramstr[0] != '\0') {
343 /*
344 * The token we're looking for should be three integers separated by
345 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
346 */
Kenny Root2947e342013-08-14 15:54:49 -0700347 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
348 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700349 i++, token = strtok_r(NULL, ":", &saveptr)) {
350 char *endptr;
351 params[i] = strtol(token, &endptr, 10);
352
353 /*
354 * Check that there was a valid number and it's 8-bit. If not,
355 * break out and the end check will take the default values.
356 */
357 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
358 break;
359 }
360 }
361
362 /*
363 * If there were not enough tokens or a token was malformed (not an
364 * integer), it will end up here and the default parameters can be
365 * taken.
366 */
367 if ((i != 3) || (token != NULL)) {
368 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
369 memcpy(params, default_params, sizeof(params));
370 }
371 }
372
373 ftr->N_factor = params[0];
374 ftr->r_factor = params[1];
375 ftr->p_factor = params[2];
376}
377
Ken Sumrall3ed82362011-01-28 23:31:16 -0800378static unsigned int get_fs_size(char *dev)
379{
380 int fd, block_size;
381 struct ext4_super_block sb;
382 off64_t len;
383
384 if ((fd = open(dev, O_RDONLY)) < 0) {
385 SLOGE("Cannot open device to get filesystem size ");
386 return 0;
387 }
388
389 if (lseek64(fd, 1024, SEEK_SET) < 0) {
390 SLOGE("Cannot seek to superblock");
391 return 0;
392 }
393
394 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
395 SLOGE("Cannot read superblock");
396 return 0;
397 }
398
399 close(fd);
400
Daniel Rosenberge82df162014-08-15 22:19:23 +0000401 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
402 SLOGE("Not a valid ext4 superblock");
403 return 0;
404 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800405 block_size = 1024 << sb.s_log_block_size;
406 /* compute length in bytes */
407 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
408
409 /* return length in sectors */
410 return (unsigned int) (len / 512);
411}
412
Ken Sumrall160b4d62013-04-22 12:15:39 -0700413static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
414{
415 static int cached_data = 0;
416 static off64_t cached_off = 0;
417 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
418 int fd;
419 char key_loc[PROPERTY_VALUE_MAX];
420 char real_blkdev[PROPERTY_VALUE_MAX];
421 unsigned int nr_sec;
422 int rc = -1;
423
424 if (!cached_data) {
425 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
426
427 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
428 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
429 SLOGE("Cannot open real block device %s\n", real_blkdev);
430 return -1;
431 }
432
433 if ((nr_sec = get_blkdev_size(fd))) {
434 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
435 * encryption info footer and key, and plenty of bytes to spare for future
436 * growth.
437 */
438 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
439 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
440 cached_data = 1;
441 } else {
442 SLOGE("Cannot get size of block device %s\n", real_blkdev);
443 }
444 close(fd);
445 } else {
446 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
447 cached_off = 0;
448 cached_data = 1;
449 }
450 }
451
452 if (cached_data) {
453 if (metadata_fname) {
454 *metadata_fname = cached_metadata_fname;
455 }
456 if (off) {
457 *off = cached_off;
458 }
459 rc = 0;
460 }
461
462 return rc;
463}
464
Ken Sumralle8744072011-01-18 22:01:55 -0800465/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800466 * update the failed mount count but not change the key.
467 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700468static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800469{
470 int fd;
471 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700472 /* starting_off is set to the SEEK_SET offset
473 * where the crypto structure starts
474 */
475 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800476 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700477 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700478 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800479
Ken Sumrall160b4d62013-04-22 12:15:39 -0700480 if (get_crypt_ftr_info(&fname, &starting_off)) {
481 SLOGE("Unable to get crypt_ftr_info\n");
482 return -1;
483 }
484 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700485 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700486 return -1;
487 }
Ken Sumralle550f782013-08-20 13:48:23 -0700488 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
489 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700490 return -1;
491 }
492
493 /* Seek to the start of the crypt footer */
494 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
495 SLOGE("Cannot seek to real block device footer\n");
496 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800497 }
498
499 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
500 SLOGE("Cannot write real block device footer\n");
501 goto errout;
502 }
503
Ken Sumrall3be890f2011-09-14 16:53:46 -0700504 fstat(fd, &statbuf);
505 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700506 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700507 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800508 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800509 goto errout;
510 }
511 }
512
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800513 /* Success! */
514 rc = 0;
515
516errout:
517 close(fd);
518 return rc;
519
520}
521
Ken Sumrall160b4d62013-04-22 12:15:39 -0700522static inline int unix_read(int fd, void* buff, int len)
523{
524 return TEMP_FAILURE_RETRY(read(fd, buff, len));
525}
526
527static inline int unix_write(int fd, const void* buff, int len)
528{
529 return TEMP_FAILURE_RETRY(write(fd, buff, len));
530}
531
532static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
533{
534 memset(pdata, 0, len);
535 pdata->persist_magic = PERSIST_DATA_MAGIC;
536 pdata->persist_valid_entries = 0;
537}
538
539/* A routine to update the passed in crypt_ftr to the lastest version.
540 * fd is open read/write on the device that holds the crypto footer and persistent
541 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
542 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
543 */
544static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
545{
Kenny Root7434b312013-06-14 11:29:53 -0700546 int orig_major = crypt_ftr->major_version;
547 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700548
Kenny Root7434b312013-06-14 11:29:53 -0700549 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
550 struct crypt_persist_data *pdata;
551 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700552
Kenny Rootc4c70f12013-06-14 12:11:38 -0700553 SLOGW("upgrading crypto footer to 1.1");
554
Kenny Root7434b312013-06-14 11:29:53 -0700555 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
556 if (pdata == NULL) {
557 SLOGE("Cannot allocate persisent data\n");
558 return;
559 }
560 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
561
562 /* Need to initialize the persistent data area */
563 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
564 SLOGE("Cannot seek to persisent data offset\n");
565 return;
566 }
567 /* Write all zeros to the first copy, making it invalid */
568 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
569
570 /* Write a valid but empty structure to the second copy */
571 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
572 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
573
574 /* Update the footer */
575 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
576 crypt_ftr->persist_data_offset[0] = pdata_offset;
577 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
578 crypt_ftr->minor_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700579 }
580
Paul Lawrencef4faa572014-01-29 13:31:03 -0800581 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700582 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800583 /* But keep the old kdf_type.
584 * It will get updated later to KDF_SCRYPT after the password has been verified.
585 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700586 crypt_ftr->kdf_type = KDF_PBKDF2;
587 get_device_scrypt_params(crypt_ftr);
588 crypt_ftr->minor_version = 2;
589 }
590
Paul Lawrencef4faa572014-01-29 13:31:03 -0800591 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
592 SLOGW("upgrading crypto footer to 1.3");
593 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
594 crypt_ftr->minor_version = 3;
595 }
596
Kenny Root7434b312013-06-14 11:29:53 -0700597 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
598 if (lseek64(fd, offset, SEEK_SET) == -1) {
599 SLOGE("Cannot seek to crypt footer\n");
600 return;
601 }
602 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700603 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700604}
605
606
607static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800608{
609 int fd;
610 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700611 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800612 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700613 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700614 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800615
Ken Sumrall160b4d62013-04-22 12:15:39 -0700616 if (get_crypt_ftr_info(&fname, &starting_off)) {
617 SLOGE("Unable to get crypt_ftr_info\n");
618 return -1;
619 }
620 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700621 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700622 return -1;
623 }
624 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700625 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700626 return -1;
627 }
628
629 /* Make sure it's 16 Kbytes in length */
630 fstat(fd, &statbuf);
631 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
632 SLOGE("footer file %s is not the expected size!\n", fname);
633 goto errout;
634 }
635
636 /* Seek to the start of the crypt footer */
637 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
638 SLOGE("Cannot seek to real block device footer\n");
639 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800640 }
641
642 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
643 SLOGE("Cannot read real block device footer\n");
644 goto errout;
645 }
646
647 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700648 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800649 goto errout;
650 }
651
Kenny Rootc96a5f82013-06-14 12:08:28 -0700652 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
653 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
654 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800655 goto errout;
656 }
657
Kenny Rootc96a5f82013-06-14 12:08:28 -0700658 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
659 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
660 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800661 }
662
Ken Sumrall160b4d62013-04-22 12:15:39 -0700663 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
664 * copy on disk before returning.
665 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700666 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700667 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800668 }
669
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800670 /* Success! */
671 rc = 0;
672
673errout:
674 close(fd);
675 return rc;
676}
677
Ken Sumrall160b4d62013-04-22 12:15:39 -0700678static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
679{
680 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
681 crypt_ftr->persist_data_offset[1]) {
682 SLOGE("Crypt_ftr persist data regions overlap");
683 return -1;
684 }
685
686 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
687 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
688 return -1;
689 }
690
691 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
692 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
693 CRYPT_FOOTER_OFFSET) {
694 SLOGE("Persistent data extends past crypto footer");
695 return -1;
696 }
697
698 return 0;
699}
700
701static int load_persistent_data(void)
702{
703 struct crypt_mnt_ftr crypt_ftr;
704 struct crypt_persist_data *pdata = NULL;
705 char encrypted_state[PROPERTY_VALUE_MAX];
706 char *fname;
707 int found = 0;
708 int fd;
709 int ret;
710 int i;
711
712 if (persist_data) {
713 /* Nothing to do, we've already loaded or initialized it */
714 return 0;
715 }
716
717
718 /* If not encrypted, just allocate an empty table and initialize it */
719 property_get("ro.crypto.state", encrypted_state, "");
720 if (strcmp(encrypted_state, "encrypted") ) {
721 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
722 if (pdata) {
723 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
724 persist_data = pdata;
725 return 0;
726 }
727 return -1;
728 }
729
730 if(get_crypt_ftr_and_key(&crypt_ftr)) {
731 return -1;
732 }
733
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700734 if ((crypt_ftr.major_version < 1)
735 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700736 SLOGE("Crypt_ftr version doesn't support persistent data");
737 return -1;
738 }
739
740 if (get_crypt_ftr_info(&fname, NULL)) {
741 return -1;
742 }
743
744 ret = validate_persistent_data_storage(&crypt_ftr);
745 if (ret) {
746 return -1;
747 }
748
749 fd = open(fname, O_RDONLY);
750 if (fd < 0) {
751 SLOGE("Cannot open %s metadata file", fname);
752 return -1;
753 }
754
755 if (persist_data == NULL) {
756 pdata = malloc(crypt_ftr.persist_data_size);
757 if (pdata == NULL) {
758 SLOGE("Cannot allocate memory for persistent data");
759 goto err;
760 }
761 }
762
763 for (i = 0; i < 2; i++) {
764 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
765 SLOGE("Cannot seek to read persistent data on %s", fname);
766 goto err2;
767 }
768 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
769 SLOGE("Error reading persistent data on iteration %d", i);
770 goto err2;
771 }
772 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
773 found = 1;
774 break;
775 }
776 }
777
778 if (!found) {
779 SLOGI("Could not find valid persistent data, creating");
780 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
781 }
782
783 /* Success */
784 persist_data = pdata;
785 close(fd);
786 return 0;
787
788err2:
789 free(pdata);
790
791err:
792 close(fd);
793 return -1;
794}
795
796static int save_persistent_data(void)
797{
798 struct crypt_mnt_ftr crypt_ftr;
799 struct crypt_persist_data *pdata;
800 char *fname;
801 off64_t write_offset;
802 off64_t erase_offset;
803 int found = 0;
804 int fd;
805 int ret;
806
807 if (persist_data == NULL) {
808 SLOGE("No persistent data to save");
809 return -1;
810 }
811
812 if(get_crypt_ftr_and_key(&crypt_ftr)) {
813 return -1;
814 }
815
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700816 if ((crypt_ftr.major_version < 1)
817 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700818 SLOGE("Crypt_ftr version doesn't support persistent data");
819 return -1;
820 }
821
822 ret = validate_persistent_data_storage(&crypt_ftr);
823 if (ret) {
824 return -1;
825 }
826
827 if (get_crypt_ftr_info(&fname, NULL)) {
828 return -1;
829 }
830
831 fd = open(fname, O_RDWR);
832 if (fd < 0) {
833 SLOGE("Cannot open %s metadata file", fname);
834 return -1;
835 }
836
837 pdata = malloc(crypt_ftr.persist_data_size);
838 if (pdata == NULL) {
839 SLOGE("Cannot allocate persistant data");
840 goto err;
841 }
842
843 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
844 SLOGE("Cannot seek to read persistent data on %s", fname);
845 goto err2;
846 }
847
848 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
849 SLOGE("Error reading persistent data before save");
850 goto err2;
851 }
852
853 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
854 /* The first copy is the curent valid copy, so write to
855 * the second copy and erase this one */
856 write_offset = crypt_ftr.persist_data_offset[1];
857 erase_offset = crypt_ftr.persist_data_offset[0];
858 } else {
859 /* The second copy must be the valid copy, so write to
860 * the first copy, and erase the second */
861 write_offset = crypt_ftr.persist_data_offset[0];
862 erase_offset = crypt_ftr.persist_data_offset[1];
863 }
864
865 /* Write the new copy first, if successful, then erase the old copy */
866 if (lseek(fd, write_offset, SEEK_SET) < 0) {
867 SLOGE("Cannot seek to write persistent data");
868 goto err2;
869 }
870 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
871 (int) crypt_ftr.persist_data_size) {
872 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
873 SLOGE("Cannot seek to erase previous persistent data");
874 goto err2;
875 }
876 fsync(fd);
877 memset(pdata, 0, crypt_ftr.persist_data_size);
878 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
879 (int) crypt_ftr.persist_data_size) {
880 SLOGE("Cannot write to erase previous persistent data");
881 goto err2;
882 }
883 fsync(fd);
884 } else {
885 SLOGE("Cannot write to save persistent data");
886 goto err2;
887 }
888
889 /* Success */
890 free(pdata);
891 close(fd);
892 return 0;
893
894err2:
895 free(pdata);
896err:
897 close(fd);
898 return -1;
899}
900
Paul Lawrencef4faa572014-01-29 13:31:03 -0800901static int hexdigit (char c)
902{
903 if (c >= '0' && c <= '9') return c - '0';
904 c = tolower(c);
905 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
906 return -1;
907}
908
909static unsigned char* convert_hex_ascii_to_key(const char* master_key_ascii,
910 unsigned int* out_keysize)
911{
912 unsigned int i;
913 *out_keysize = 0;
914
915 size_t size = strlen (master_key_ascii);
916 if (size % 2) {
917 SLOGE("Trying to convert ascii string of odd length");
918 return NULL;
919 }
920
921 unsigned char* master_key = (unsigned char*) malloc(size / 2);
922 if (master_key == 0) {
923 SLOGE("Cannot allocate");
924 return NULL;
925 }
926
927 for (i = 0; i < size; i += 2) {
928 int high_nibble = hexdigit (master_key_ascii[i]);
929 int low_nibble = hexdigit (master_key_ascii[i + 1]);
930
931 if(high_nibble < 0 || low_nibble < 0) {
932 SLOGE("Invalid hex string");
933 free (master_key);
934 return NULL;
935 }
936
937 master_key[*out_keysize] = high_nibble * 16 + low_nibble;
938 (*out_keysize)++;
939 }
940
941 return master_key;
942}
943
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800944/* Convert a binary key of specified length into an ascii hex string equivalent,
945 * without the leading 0x and with null termination
946 */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800947static void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800948 char *master_key_ascii)
949{
950 unsigned int i, a;
951 unsigned char nibble;
952
953 for (i=0, a=0; i<keysize; i++, a+=2) {
954 /* For each byte, write out two ascii hex digits */
955 nibble = (master_key[i] >> 4) & 0xf;
956 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
957
958 nibble = master_key[i] & 0xf;
959 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
960 }
961
962 /* Add the null termination */
963 master_key_ascii[a] = '\0';
964
965}
966
Ken Sumralldb5e0262013-02-05 17:39:48 -0800967static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
968 char *real_blk_name, const char *name, int fd,
969 char *extra_params)
970{
971 char buffer[DM_CRYPT_BUF_SIZE];
972 struct dm_ioctl *io;
973 struct dm_target_spec *tgt;
974 char *crypt_params;
975 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
976 int i;
977
978 io = (struct dm_ioctl *) buffer;
979
980 /* Load the mapping table for this device */
981 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
982
983 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
984 io->target_count = 1;
985 tgt->status = 0;
986 tgt->sector_start = 0;
987 tgt->length = crypt_ftr->fs_size;
988 strcpy(tgt->target_type, "crypt");
989
990 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
991 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
992 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
993 master_key_ascii, real_blk_name, extra_params);
994 crypt_params += strlen(crypt_params) + 1;
995 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
996 tgt->next = crypt_params - buffer;
997
998 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
999 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
1000 break;
1001 }
1002 usleep(500000);
1003 }
1004
1005 if (i == TABLE_LOAD_RETRIES) {
1006 /* We failed to load the table, return an error */
1007 return -1;
1008 } else {
1009 return i + 1;
1010 }
1011}
1012
1013
1014static int get_dm_crypt_version(int fd, const char *name, int *version)
1015{
1016 char buffer[DM_CRYPT_BUF_SIZE];
1017 struct dm_ioctl *io;
1018 struct dm_target_versions *v;
1019 int i;
1020
1021 io = (struct dm_ioctl *) buffer;
1022
1023 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1024
1025 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1026 return -1;
1027 }
1028
1029 /* Iterate over the returned versions, looking for name of "crypt".
1030 * When found, get and return the version.
1031 */
1032 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1033 while (v->next) {
1034 if (! strcmp(v->name, "crypt")) {
1035 /* We found the crypt driver, return the version, and get out */
1036 version[0] = v->version[0];
1037 version[1] = v->version[1];
1038 version[2] = v->version[2];
1039 return 0;
1040 }
1041 v = (struct dm_target_versions *)(((char *)v) + v->next);
1042 }
1043
1044 return -1;
1045}
1046
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001047static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -07001048 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001049{
1050 char buffer[DM_CRYPT_BUF_SIZE];
1051 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
1052 char *crypt_params;
1053 struct dm_ioctl *io;
1054 struct dm_target_spec *tgt;
1055 unsigned int minor;
1056 int fd;
Ken Sumralle919efe2012-09-29 17:07:41 -07001057 int i;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001058 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001059 int version[3];
1060 char *extra_params;
1061 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001062
1063 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1064 SLOGE("Cannot open device-mapper\n");
1065 goto errout;
1066 }
1067
1068 io = (struct dm_ioctl *) buffer;
1069
1070 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1071 if (ioctl(fd, DM_DEV_CREATE, io)) {
1072 SLOGE("Cannot create dm-crypt device\n");
1073 goto errout;
1074 }
1075
1076 /* Get the device status, in particular, the name of it's device file */
1077 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1078 if (ioctl(fd, DM_DEV_STATUS, io)) {
1079 SLOGE("Cannot retrieve dm-crypt device status\n");
1080 goto errout;
1081 }
1082 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1083 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1084
Ken Sumralldb5e0262013-02-05 17:39:48 -08001085 extra_params = "";
1086 if (! get_dm_crypt_version(fd, name, version)) {
1087 /* Support for allow_discards was added in version 1.11.0 */
1088 if ((version[0] >= 2) ||
1089 ((version[0] == 1) && (version[1] >= 11))) {
1090 extra_params = "1 allow_discards";
1091 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1092 }
Ken Sumralle919efe2012-09-29 17:07:41 -07001093 }
1094
Ken Sumralldb5e0262013-02-05 17:39:48 -08001095 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1096 fd, extra_params);
1097 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001098 SLOGE("Cannot load dm-crypt mapping table.\n");
1099 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001100 } else if (load_count > 1) {
1101 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001102 }
1103
1104 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -08001105 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001106
1107 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1108 SLOGE("Cannot resume the dm-crypt device\n");
1109 goto errout;
1110 }
1111
1112 /* We made it here with no errors. Woot! */
1113 retval = 0;
1114
1115errout:
1116 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1117
1118 return retval;
1119}
1120
Ken Sumrall29d8da82011-05-18 17:20:07 -07001121static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001122{
1123 int fd;
1124 char buffer[DM_CRYPT_BUF_SIZE];
1125 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001126 int retval = -1;
1127
1128 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1129 SLOGE("Cannot open device-mapper\n");
1130 goto errout;
1131 }
1132
1133 io = (struct dm_ioctl *) buffer;
1134
1135 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1136 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1137 SLOGE("Cannot remove dm-crypt device\n");
1138 goto errout;
1139 }
1140
1141 /* We made it here with no errors. Woot! */
1142 retval = 0;
1143
1144errout:
1145 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1146
1147 return retval;
1148
1149}
1150
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001151static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001152 unsigned char *ikey, void *params UNUSED)
1153{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001154 SLOGI("Using pbkdf2 for cryptfs KDF");
1155
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001156 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001157 unsigned int keysize;
1158 char* master_key = (char*)convert_hex_ascii_to_key(passwd, &keysize);
1159 if (!master_key) return -1;
1160 PKCS5_PBKDF2_HMAC_SHA1(master_key, keysize, salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001161 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001162
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001163 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001164 free (master_key);
1165 return 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001166}
1167
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001168static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001169 unsigned char *ikey, void *params)
1170{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001171 SLOGI("Using scrypt for cryptfs KDF");
1172
Kenny Rootc4c70f12013-06-14 12:11:38 -07001173 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1174
1175 int N = 1 << ftr->N_factor;
1176 int r = 1 << ftr->r_factor;
1177 int p = 1 << ftr->p_factor;
1178
1179 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001180 unsigned int keysize;
1181 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &keysize);
1182 if (!master_key) return -1;
1183 crypto_scrypt(master_key, keysize, salt, SALT_LEN, N, r, p, ikey,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001184 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001185
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001186 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001187 free (master_key);
1188 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001189}
1190
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001191static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1192 unsigned char *ikey, void *params)
1193{
1194 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1195
1196 int rc;
1197 unsigned int key_size;
1198 size_t signature_size;
1199 unsigned char* signature;
1200 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1201
1202 int N = 1 << ftr->N_factor;
1203 int r = 1 << ftr->r_factor;
1204 int p = 1 << ftr->p_factor;
1205
1206 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &key_size);
1207 if (!master_key) {
1208 SLOGE("Failed to convert passwd from hex");
1209 return -1;
1210 }
1211
1212 rc = crypto_scrypt(master_key, key_size, salt, SALT_LEN,
1213 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1214 memset(master_key, 0, key_size);
1215 free(master_key);
1216
1217 if (rc) {
1218 SLOGE("scrypt failed");
1219 return -1;
1220 }
1221
Shawn Willdene17a9c42014-09-08 13:04:08 -06001222 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1223 &signature, &signature_size)) {
1224 SLOGE("Signing failed");
1225 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001226 }
1227
1228 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1229 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1230 free(signature);
1231
1232 if (rc) {
1233 SLOGE("scrypt failed");
1234 return -1;
1235 }
1236
1237 return 0;
1238}
1239
1240static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1241 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001242 unsigned char *encrypted_master_key,
1243 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001244{
1245 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1246 EVP_CIPHER_CTX e_ctx;
1247 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001248 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001249
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001250 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001251 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001252
1253 switch (crypt_ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001254 case KDF_SCRYPT_KEYMASTER_UNPADDED:
1255 case KDF_SCRYPT_KEYMASTER_BADLY_PADDED:
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 Willdene17a9c42014-09-08 13:04:08 -06001374 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER_UNPADDED ||
1375 ftr->kdf_type == KDF_SCRYPT_KEYMASTER_BADLY_PADDED ||
1376 ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001377 *kdf = scrypt_keymaster;
1378 *kdf_params = ftr;
1379 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001380 *kdf = scrypt;
1381 *kdf_params = ftr;
1382 } else {
1383 *kdf = pbkdf2;
1384 *kdf_params = NULL;
1385 }
1386}
1387
JP Abgrall7bdfa522013-11-15 13:42:56 -08001388static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001389 struct crypt_mnt_ftr *crypt_ftr,
1390 unsigned char** intermediate_key,
1391 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001392{
1393 kdf_func kdf;
1394 void *kdf_params;
1395 int ret;
1396
1397 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001398 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1399 decrypted_master_key, kdf, kdf_params,
1400 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001401 if (ret != 0) {
1402 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001403 }
1404
1405 return ret;
1406}
1407
1408static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1409 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001410 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001411 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001412 EVP_CIPHER_CTX e_ctx;
1413 int encrypted_len, final_len;
1414
1415 /* Get some random bits for a key */
1416 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001417 read(fd, key_buf, sizeof(key_buf));
1418 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001419 close(fd);
1420
1421 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001422 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001423}
1424
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001425static int wait_and_unmount(char *mountpoint)
1426{
1427 int i, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001428#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001429
1430 /* Now umount the tmpfs filesystem */
1431 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
1432 if (umount(mountpoint)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001433 if (errno == EINVAL) {
1434 /* EINVAL is returned if the directory is not a mountpoint,
1435 * i.e. there is no filesystem mounted there. So just get out.
1436 */
1437 break;
1438 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001439 sleep(1);
1440 i++;
1441 } else {
1442 break;
1443 }
1444 }
1445
1446 if (i < WAIT_UNMOUNT_COUNT) {
1447 SLOGD("unmounting %s succeeded\n", mountpoint);
1448 rc = 0;
1449 } else {
1450 SLOGE("unmounting %s failed\n", mountpoint);
1451 rc = -1;
1452 }
1453
1454 return rc;
1455}
1456
Ken Sumrallc5872692013-05-14 15:26:31 -07001457#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001458static int prep_data_fs(void)
1459{
1460 int i;
1461
1462 /* Do the prep of the /data filesystem */
1463 property_set("vold.post_fs_data_done", "0");
1464 property_set("vold.decrypt", "trigger_post_fs_data");
1465 SLOGD("Just triggered post_fs_data\n");
1466
Ken Sumrallc5872692013-05-14 15:26:31 -07001467 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001468 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001469 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001470
1471 property_get("vold.post_fs_data_done", p, "0");
1472 if (*p == '1') {
1473 break;
1474 } else {
1475 usleep(250000);
1476 }
1477 }
1478 if (i == DATA_PREP_TIMEOUT) {
1479 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001480 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001481 return -1;
1482 } else {
1483 SLOGD("post_fs_data done\n");
1484 return 0;
1485 }
1486}
1487
Paul Lawrence74f29f12014-08-28 15:54:10 -07001488static void cryptfs_set_corrupt()
1489{
1490 // Mark the footer as bad
1491 struct crypt_mnt_ftr crypt_ftr;
1492 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1493 SLOGE("Failed to get crypto footer - panic");
1494 return;
1495 }
1496
1497 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1498 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1499 SLOGE("Failed to set crypto footer - panic");
1500 return;
1501 }
1502}
1503
1504static void cryptfs_trigger_restart_min_framework()
1505{
1506 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1507 SLOGE("Failed to mount tmpfs on data - panic");
1508 return;
1509 }
1510
1511 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1512 SLOGE("Failed to trigger post fs data - panic");
1513 return;
1514 }
1515
1516 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1517 SLOGE("Failed to trigger restart min framework - panic");
1518 return;
1519 }
1520}
1521
Paul Lawrencef4faa572014-01-29 13:31:03 -08001522static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001523{
1524 char fs_type[32];
1525 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001526 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001527 char fs_options[256];
1528 unsigned long mnt_flags;
1529 struct stat statbuf;
1530 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001531 static int restart_successful = 0;
1532
1533 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001534 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001535 SLOGE("Encrypted filesystem not validated, aborting");
1536 return -1;
1537 }
1538
1539 if (restart_successful) {
1540 SLOGE("System already restarted with encrypted disk, aborting");
1541 return -1;
1542 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001543
Paul Lawrencef4faa572014-01-29 13:31:03 -08001544 if (restart_main) {
1545 /* Here is where we shut down the framework. The init scripts
1546 * start all services in one of three classes: core, main or late_start.
1547 * On boot, we start core and main. Now, we stop main, but not core,
1548 * as core includes vold and a few other really important things that
1549 * we need to keep running. Once main has stopped, we should be able
1550 * to umount the tmpfs /data, then mount the encrypted /data.
1551 * We then restart the class main, and also the class late_start.
1552 * At the moment, I've only put a few things in late_start that I know
1553 * are not needed to bring up the framework, and that also cause problems
1554 * with unmounting the tmpfs /data, but I hope to add add more services
1555 * to the late_start class as we optimize this to decrease the delay
1556 * till the user is asked for the password to the filesystem.
1557 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001558
Paul Lawrencef4faa572014-01-29 13:31:03 -08001559 /* The init files are setup to stop the class main when vold.decrypt is
1560 * set to trigger_reset_main.
1561 */
1562 property_set("vold.decrypt", "trigger_reset_main");
1563 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001564
Paul Lawrencef4faa572014-01-29 13:31:03 -08001565 /* Ugh, shutting down the framework is not synchronous, so until it
1566 * can be fixed, this horrible hack will wait a moment for it all to
1567 * shut down before proceeding. Without it, some devices cannot
1568 * restart the graphics services.
1569 */
1570 sleep(2);
1571 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001572
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001573 /* Now that the framework is shutdown, we should be able to umount()
1574 * the tmpfs filesystem, and mount the real one.
1575 */
1576
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001577 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1578 if (strlen(crypto_blkdev) == 0) {
1579 SLOGE("fs_crypto_blkdev not set\n");
1580 return -1;
1581 }
1582
Ken Sumralle5032c42012-04-01 23:58:44 -07001583 if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001584 /* If ro.crypto.readonly is set to 1, mount the decrypted
1585 * filesystem readonly. This is used when /data is mounted by
1586 * recovery mode.
1587 */
1588 char ro_prop[PROPERTY_VALUE_MAX];
1589 property_get("ro.crypto.readonly", ro_prop, "");
1590 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1591 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1592 rec->flags |= MS_RDONLY;
1593 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001594
Ken Sumralle5032c42012-04-01 23:58:44 -07001595 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001596 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, 0)) {
1597 SLOGE("Failed to mount decrypted data");
1598 cryptfs_set_corrupt();
1599 cryptfs_trigger_restart_min_framework();
1600 SLOGI("Started framework to offer wipe");
1601 return -1;
1602 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001603
Ken Sumralle5032c42012-04-01 23:58:44 -07001604 property_set("vold.decrypt", "trigger_load_persist_props");
1605 /* Create necessary paths on /data */
1606 if (prep_data_fs()) {
1607 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001608 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001609
1610 /* startup service classes main and late_start */
1611 property_set("vold.decrypt", "trigger_restart_framework");
1612 SLOGD("Just triggered restart_framework\n");
1613
1614 /* Give it a few moments to get started */
1615 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001616 }
1617
Ken Sumrall0cc16632011-01-18 20:32:26 -08001618 if (rc == 0) {
1619 restart_successful = 1;
1620 }
1621
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001622 return rc;
1623}
1624
Paul Lawrencef4faa572014-01-29 13:31:03 -08001625int cryptfs_restart(void)
1626{
1627 /* Call internal implementation forcing a restart of main service group */
1628 return cryptfs_restart_internal(1);
1629}
1630
Mark Salyzyn3e971272014-01-21 13:27:04 -08001631static int do_crypto_complete(char *mount_point UNUSED)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001632{
1633 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001634 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001635 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001636
1637 property_get("ro.crypto.state", encrypted_state, "");
1638 if (strcmp(encrypted_state, "encrypted") ) {
1639 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001640 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001641 }
1642
Ken Sumrall160b4d62013-04-22 12:15:39 -07001643 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001644 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001645
Ken Sumralle1a45852011-12-14 21:24:27 -08001646 /*
1647 * Only report this error if key_loc is a file and it exists.
1648 * If the device was never encrypted, and /data is not mountable for
1649 * some reason, returning 1 should prevent the UI from presenting the
1650 * a "enter password" screen, or worse, a "press button to wipe the
1651 * device" screen.
1652 */
1653 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1654 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001655 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001656 } else {
1657 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001658 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001659 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001660 }
1661
Paul Lawrence74f29f12014-08-28 15:54:10 -07001662 // Test for possible error flags
1663 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1664 SLOGE("Encryption process is partway completed\n");
1665 return CRYPTO_COMPLETE_PARTIAL;
1666 }
1667
1668 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1669 SLOGE("Encryption process was interrupted but cannot continue\n");
1670 return CRYPTO_COMPLETE_INCONSISTENT;
1671 }
1672
1673 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1674 SLOGE("Encryption is successful but data is corrupt\n");
1675 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001676 }
1677
1678 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001679 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001680}
1681
Paul Lawrencef4faa572014-01-29 13:31:03 -08001682static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1683 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001684{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001685 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001686 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001687 char crypto_blkdev[MAXPATHLEN];
1688 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001689 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001690 unsigned int orig_failed_decrypt_count;
1691 int rc;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001692 kdf_func kdf;
1693 void *kdf_params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001694 int use_keymaster = 0;
1695 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001696 unsigned char* intermediate_key = 0;
1697 size_t intermediate_key_size = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001698
Paul Lawrencef4faa572014-01-29 13:31:03 -08001699 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1700 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001701
Paul Lawrencef4faa572014-01-29 13:31:03 -08001702 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001703 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1704 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001705 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001706 rc = -1;
1707 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001708 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001709 }
1710
Paul Lawrencef4faa572014-01-29 13:31:03 -08001711 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1712
Paul Lawrence74f29f12014-08-28 15:54:10 -07001713 // Create crypto block device - all (non fatal) code paths
1714 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001715 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1716 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001717 SLOGE("Error creating decrypted block device\n");
1718 rc = -1;
1719 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001720 }
1721
Paul Lawrence74f29f12014-08-28 15:54:10 -07001722 /* Work out if the problem is the password or the data */
1723 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1724 scrypted_intermediate_key)];
1725 int N = 1 << crypt_ftr->N_factor;
1726 int r = 1 << crypt_ftr->r_factor;
1727 int p = 1 << crypt_ftr->p_factor;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001728
Paul Lawrence74f29f12014-08-28 15:54:10 -07001729 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1730 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1731 N, r, p, scrypted_intermediate_key,
1732 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001733
Paul Lawrence74f29f12014-08-28 15:54:10 -07001734 // Does the key match the crypto footer?
1735 if (rc == 0 && memcmp(scrypted_intermediate_key,
1736 crypt_ftr->scrypted_intermediate_key,
1737 sizeof(scrypted_intermediate_key)) == 0) {
1738 SLOGI("Password matches");
1739 rc = 0;
1740 } else {
1741 /* Try mounting the file system anyway, just in case the problem's with
1742 * the footer, not the key. */
1743 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1744 mkdir(tmp_mount_point, 0755);
1745 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1746 SLOGE("Error temp mounting decrypted block device\n");
1747 delete_crypto_blk_dev(label);
1748
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001749 rc = ++crypt_ftr->failed_decrypt_count;
1750 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001751 } else {
1752 /* Success! */
1753 SLOGI("Password did not match but decrypted drive mounted - continue");
1754 umount(tmp_mount_point);
1755 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001756 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001757 }
1758
1759 if (rc == 0) {
1760 crypt_ftr->failed_decrypt_count = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001761
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001762 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001763 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001764 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001765
1766 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001767 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001768 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001769 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001770 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001771 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001772 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001773
Paul Lawrence74f29f12014-08-28 15:54:10 -07001774 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001775 use_keymaster = keymaster_check_compatibility();
1776 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001777 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001778 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1779 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1780 upgrade = 1;
1781 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001782 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001783 upgrade = 1;
1784 }
1785
1786 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001787 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1788 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001789 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001790 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001791 }
1792 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001793
1794 // Do not fail even if upgrade failed - machine is bootable
1795 // Note that if this code is ever hit, there is a *serious* problem
1796 // since KDFs should never fail. You *must* fix the kdf before
1797 // proceeding!
1798 if (rc) {
1799 SLOGW("Upgrade failed with error %d,"
1800 " but continuing with previous state",
1801 rc);
1802 rc = 0;
1803 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001804 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001805 }
1806
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001807 errout:
1808 if (intermediate_key) {
1809 memset(intermediate_key, 0, intermediate_key_size);
1810 free(intermediate_key);
1811 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001812 return rc;
1813}
1814
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001815/* Called by vold when it wants to undo the crypto mapping of a volume it
1816 * manages. This is usually in response to a factory reset, when we want
1817 * to undo the crypto mapping so the volume is formatted in the clear.
1818 */
1819int cryptfs_revert_volume(const char *label)
1820{
1821 return delete_crypto_blk_dev((char *)label);
1822}
1823
Ken Sumrall29d8da82011-05-18 17:20:07 -07001824/*
1825 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1826 * Setup a dm-crypt mapping, use the saved master key from
1827 * setting up the /data mapping, and return the new device path.
1828 */
1829int cryptfs_setup_volume(const char *label, int major, int minor,
1830 char *crypto_sys_path, unsigned int max_path,
1831 int *new_major, int *new_minor)
1832{
1833 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1834 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001835 struct stat statbuf;
1836 int nr_sec, fd;
1837
1838 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1839
Ken Sumrall160b4d62013-04-22 12:15:39 -07001840 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001841
1842 /* Update the fs_size field to be the size of the volume */
1843 fd = open(real_blkdev, O_RDONLY);
1844 nr_sec = get_blkdev_size(fd);
1845 close(fd);
1846 if (nr_sec == 0) {
1847 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1848 return -1;
1849 }
1850
1851 sd_crypt_ftr.fs_size = nr_sec;
1852 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1853 crypto_blkdev, label);
1854
1855 stat(crypto_blkdev, &statbuf);
1856 *new_major = MAJOR(statbuf.st_rdev);
1857 *new_minor = MINOR(statbuf.st_rdev);
1858
1859 /* Create path to sys entry for this block device */
1860 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1861
1862 return 0;
1863}
1864
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001865int cryptfs_crypto_complete(void)
1866{
1867 return do_crypto_complete("/data");
1868}
1869
Paul Lawrencef4faa572014-01-29 13:31:03 -08001870int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1871{
1872 char encrypted_state[PROPERTY_VALUE_MAX];
1873 property_get("ro.crypto.state", encrypted_state, "");
1874 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1875 SLOGE("encrypted fs already validated or not running with encryption,"
1876 " aborting");
1877 return -1;
1878 }
1879
1880 if (get_crypt_ftr_and_key(crypt_ftr)) {
1881 SLOGE("Error getting crypt footer and key");
1882 return -1;
1883 }
1884
1885 return 0;
1886}
1887
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001888int cryptfs_check_passwd(char *passwd)
1889{
Paul Lawrencef4faa572014-01-29 13:31:03 -08001890 struct crypt_mnt_ftr crypt_ftr;
1891 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001892
Paul Lawrencef4faa572014-01-29 13:31:03 -08001893 rc = check_unmounted_and_get_ftr(&crypt_ftr);
1894 if (rc)
1895 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001896
Paul Lawrencef4faa572014-01-29 13:31:03 -08001897 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
1898 DATA_MNT_POINT, "userdata");
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001899
1900 if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001901 cryptfs_clear_password();
1902 password = strdup(passwd);
1903 struct timespec now;
1904 clock_gettime(CLOCK_BOOTTIME, &now);
1905 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001906 }
1907
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001908 return rc;
1909}
1910
Ken Sumrall3ad90722011-10-04 20:38:29 -07001911int cryptfs_verify_passwd(char *passwd)
1912{
1913 struct crypt_mnt_ftr crypt_ftr;
1914 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001915 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001916 char encrypted_state[PROPERTY_VALUE_MAX];
1917 int rc;
1918
1919 property_get("ro.crypto.state", encrypted_state, "");
1920 if (strcmp(encrypted_state, "encrypted") ) {
1921 SLOGE("device not encrypted, aborting");
1922 return -2;
1923 }
1924
1925 if (!master_key_saved) {
1926 SLOGE("encrypted fs not yet mounted, aborting");
1927 return -1;
1928 }
1929
1930 if (!saved_mount_point) {
1931 SLOGE("encrypted fs failed to save mount point, aborting");
1932 return -1;
1933 }
1934
Ken Sumrall160b4d62013-04-22 12:15:39 -07001935 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001936 SLOGE("Error getting crypt footer and key\n");
1937 return -1;
1938 }
1939
1940 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1941 /* If the device has no password, then just say the password is valid */
1942 rc = 0;
1943 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001944 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001945 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1946 /* They match, the password is correct */
1947 rc = 0;
1948 } else {
1949 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1950 sleep(1);
1951 rc = 1;
1952 }
1953 }
1954
1955 return rc;
1956}
1957
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001958/* Initialize a crypt_mnt_ftr structure. The keysize is
1959 * defaulted to 16 bytes, and the filesystem size to 0.
1960 * Presumably, at a minimum, the caller will update the
1961 * filesystem size and crypto_type_name after calling this function.
1962 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001963static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001964{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001965 off64_t off;
1966
1967 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001968 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001969 ftr->major_version = CURRENT_MAJOR_VERSION;
1970 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001971 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001972 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001973
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001974 switch (keymaster_check_compatibility()) {
1975 case 1:
1976 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1977 break;
1978
1979 case 0:
1980 ftr->kdf_type = KDF_SCRYPT;
1981 break;
1982
1983 default:
1984 SLOGE("keymaster_check_compatibility failed");
1985 return -1;
1986 }
1987
Kenny Rootc4c70f12013-06-14 12:11:38 -07001988 get_device_scrypt_params(ftr);
1989
Ken Sumrall160b4d62013-04-22 12:15:39 -07001990 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1991 if (get_crypt_ftr_info(NULL, &off) == 0) {
1992 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1993 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1994 ftr->persist_data_size;
1995 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001996
1997 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001998}
1999
Ken Sumrall29d8da82011-05-18 17:20:07 -07002000static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002001{
Ken Sumralle550f782013-08-20 13:48:23 -07002002 const char *args[10];
2003 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
2004 int num_args;
2005 int status;
2006 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002007 int rc = -1;
2008
Ken Sumrall29d8da82011-05-18 17:20:07 -07002009 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07002010 args[0] = "/system/bin/make_ext4fs";
2011 args[1] = "-a";
2012 args[2] = "/data";
2013 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07002014 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07002015 args[4] = size_str;
2016 args[5] = crypto_blkdev;
2017 num_args = 6;
2018 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
2019 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07002020 } else if (type == F2FS_FS) {
2021 args[0] = "/system/bin/mkfs.f2fs";
2022 args[1] = "-t";
2023 args[2] = "-d1";
2024 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07002025 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07002026 args[4] = size_str;
2027 num_args = 5;
2028 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
2029 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002030 } else {
2031 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
2032 return -1;
2033 }
2034
Ken Sumralle550f782013-08-20 13:48:23 -07002035 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
2036
2037 if (tmp != 0) {
2038 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002039 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07002040 if (WIFEXITED(status)) {
2041 if (WEXITSTATUS(status)) {
2042 SLOGE("Error creating filesystem on %s, exit status %d ",
2043 crypto_blkdev, WEXITSTATUS(status));
2044 } else {
2045 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
2046 rc = 0;
2047 }
2048 } else {
2049 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
2050 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002051 }
2052
2053 return rc;
2054}
2055
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002056#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08002057#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
2058#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002059
2060/* aligned 32K writes tends to make flash happy.
2061 * SD card association recommends it.
2062 */
2063#define BLOCKS_AT_A_TIME 8
2064
2065struct encryptGroupsData
2066{
2067 int realfd;
2068 int cryptofd;
2069 off64_t numblocks;
2070 off64_t one_pct, cur_pct, new_pct;
2071 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002072 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002073 char* real_blkdev, * crypto_blkdev;
2074 int count;
2075 off64_t offset;
2076 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08002077 off64_t last_written_sector;
2078 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002079 time_t time_started;
2080 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002081};
2082
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002083static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002084{
2085 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002086
2087 if (is_used) {
2088 data->used_blocks_already_done++;
2089 }
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002090 if (data->tot_used_blocks) {
2091 data->new_pct = data->used_blocks_already_done / data->one_pct;
2092 } else {
2093 data->new_pct = data->blocks_already_done / data->one_pct;
2094 }
2095
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002096 if (data->new_pct > data->cur_pct) {
2097 char buf[8];
2098 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07002099 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002100 property_set("vold.encrypt_progress", buf);
Elliott Hughescb33f572014-06-25 18:25:11 -07002101 SLOGI("Encrypted %" PRId64 " percent of drive", data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002102 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002103
2104 if (data->cur_pct >= 5) {
2105 double elapsed_time = difftime(time(NULL), data->time_started);
2106 off64_t remaining_blocks = data->tot_used_blocks
2107 - data->used_blocks_already_done;
2108 int remaining_time = (int)(elapsed_time * remaining_blocks
2109 / data->used_blocks_already_done);
Paul Lawrence71577502014-08-13 14:55:55 -07002110
2111 // Change time only if not yet set, lower, or a lot higher for
2112 // best user experience
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002113 if (data->remaining_time == -1
Paul Lawrence71577502014-08-13 14:55:55 -07002114 || remaining_time < data->remaining_time
2115 || remaining_time > data->remaining_time + 60) {
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002116 char buf[8];
2117 snprintf(buf, sizeof(buf), "%d", remaining_time);
2118 property_set("vold.encrypt_time_remaining", buf);
2119
Elliott Hughescb33f572014-06-25 18:25:11 -07002120 SLOGI("Encrypted %" PRId64 " percent of drive, %d seconds to go",
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002121 data->cur_pct, remaining_time);
2122 data->remaining_time = remaining_time;
2123 }
2124 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002125}
2126
2127static int flush_outstanding_data(struct encryptGroupsData* data)
2128{
2129 if (data->count == 0) {
2130 return 0;
2131 }
2132
Elliott Hughes231bdba2014-06-25 18:36:19 -07002133 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002134
2135 if (pread64(data->realfd, data->buffer,
2136 info.block_size * data->count, data->offset)
2137 <= 0) {
2138 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2139 data->real_blkdev);
2140 return -1;
2141 }
2142
2143 if (pwrite64(data->cryptofd, data->buffer,
2144 info.block_size * data->count, data->offset)
2145 <= 0) {
2146 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2147 data->crypto_blkdev);
2148 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002149 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002150 SLOGI("Encrypted %d blocks at sector %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002151 data->count, data->offset / info.block_size * CRYPT_SECTOR_SIZE);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002152 }
2153
2154 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002155 data->last_written_sector = (data->offset + data->count)
2156 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002157 return 0;
2158}
2159
2160static int encrypt_groups(struct encryptGroupsData* data)
2161{
2162 unsigned int i;
2163 u8 *block_bitmap = 0;
2164 unsigned int block;
2165 off64_t ret;
2166 int rc = -1;
2167
2168 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
2169 if (!data->buffer) {
2170 SLOGE("Failed to allocate crypto buffer");
2171 goto errout;
2172 }
2173
2174 block_bitmap = malloc(info.block_size);
2175 if (!block_bitmap) {
2176 SLOGE("failed to allocate block bitmap");
2177 goto errout;
2178 }
2179
2180 for (i = 0; i < aux_info.groups; ++i) {
2181 SLOGI("Encrypting group %d", i);
2182
2183 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2184 u32 block_count = min(info.blocks_per_group,
2185 aux_info.len_blocks - first_block);
2186
2187 off64_t offset = (u64)info.block_size
2188 * aux_info.bg_desc[i].bg_block_bitmap;
2189
2190 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2191 if (ret != (int)info.block_size) {
2192 SLOGE("failed to read all of block group bitmap %d", i);
2193 goto errout;
2194 }
2195
2196 offset = (u64)info.block_size * first_block;
2197
2198 data->count = 0;
2199
2200 for (block = 0; block < block_count; block++) {
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002201 int used = bitmap_get_bit(block_bitmap, block);
2202 update_progress(data, used);
2203 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002204 if (data->count == 0) {
2205 data->offset = offset;
2206 }
2207 data->count++;
2208 } else {
2209 if (flush_outstanding_data(data)) {
2210 goto errout;
2211 }
2212 }
2213
2214 offset += info.block_size;
2215
2216 /* Write data if we are aligned or buffer size reached */
2217 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2218 || data->count == BLOCKS_AT_A_TIME) {
2219 if (flush_outstanding_data(data)) {
2220 goto errout;
2221 }
2222 }
Paul Lawrence87999172014-02-20 12:21:31 -08002223
Paul Lawrence73d7a022014-06-09 14:10:09 -07002224 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002225 SLOGE("Stopping encryption due to low battery");
2226 rc = 0;
2227 goto errout;
2228 }
2229
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002230 }
2231 if (flush_outstanding_data(data)) {
2232 goto errout;
2233 }
2234 }
2235
Paul Lawrence87999172014-02-20 12:21:31 -08002236 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002237 rc = 0;
2238
2239errout:
2240 free(data->buffer);
2241 free(block_bitmap);
2242 return rc;
2243}
2244
2245static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2246 char *real_blkdev,
2247 off64_t size,
2248 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002249 off64_t tot_size,
2250 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002251{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002252 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002253 struct encryptGroupsData data;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002254 int rc; // Can't initialize without causing warning -Wclobbered
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002255
Paul Lawrence87999172014-02-20 12:21:31 -08002256 if (previously_encrypted_upto > *size_already_done) {
2257 SLOGD("Not fast encrypting since resuming part way through");
2258 return -1;
2259 }
2260
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002261 memset(&data, 0, sizeof(data));
2262 data.real_blkdev = real_blkdev;
2263 data.crypto_blkdev = crypto_blkdev;
2264
2265 if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
2266 SLOGE("Error opening real_blkdev %s for inplace encrypt\n",
2267 real_blkdev);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002268 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002269 goto errout;
2270 }
2271
2272 if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
2273 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n",
2274 crypto_blkdev);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002275 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002276 goto errout;
2277 }
2278
2279 if (setjmp(setjmp_env)) {
2280 SLOGE("Reading extent caused an exception");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002281 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002282 goto errout;
2283 }
2284
2285 if (read_ext(data.realfd, 0) != 0) {
2286 SLOGE("Failed to read extent");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002287 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002288 goto errout;
2289 }
2290
2291 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2292 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2293 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2294
2295 SLOGI("Encrypting filesystem in place...");
2296
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002297 data.tot_used_blocks = data.numblocks;
2298 for (i = 0; i < aux_info.groups; ++i) {
2299 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2300 }
2301
2302 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002303 data.cur_pct = 0;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002304 data.time_started = time(NULL);
2305 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002306
2307 rc = encrypt_groups(&data);
2308 if (rc) {
2309 SLOGE("Error encrypting groups");
2310 goto errout;
2311 }
2312
Paul Lawrence87999172014-02-20 12:21:31 -08002313 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002314 rc = 0;
2315
2316errout:
2317 close(data.realfd);
2318 close(data.cryptofd);
2319
2320 return rc;
2321}
2322
Daniel Rosenberge82df162014-08-15 22:19:23 +00002323static int encrypt_one_block_f2fs(u64 pos, void *data)
2324{
2325 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2326
2327 priv_dat->blocks_already_done = pos - 1;
2328 update_progress(priv_dat, 1);
2329
2330 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2331
2332 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
2333 SLOGE("Error reading real_blkdev %s for inplace encrypt", priv_dat->crypto_blkdev);
2334 return -1;
2335 }
2336
2337 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
2338 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", priv_dat->crypto_blkdev);
2339 return -1;
2340 } else {
2341 SLOGD("Encrypted block %"PRIu64, pos);
2342 }
2343
2344 return 0;
2345}
2346
2347static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2348 char *real_blkdev,
2349 off64_t size,
2350 off64_t *size_already_done,
2351 off64_t tot_size,
2352 off64_t previously_encrypted_upto)
2353{
2354 u32 i;
2355 struct encryptGroupsData data;
2356 struct f2fs_info *f2fs_info = NULL;
2357 int rc = -1;
2358 if (previously_encrypted_upto > *size_already_done) {
2359 SLOGD("Not fast encrypting since resuming part way through");
2360 return -1;
2361 }
2362 memset(&data, 0, sizeof(data));
2363 data.real_blkdev = real_blkdev;
2364 data.crypto_blkdev = crypto_blkdev;
2365 data.realfd = -1;
2366 data.cryptofd = -1;
2367 if ( (data.realfd = open64(real_blkdev, O_RDWR)) < 0) {
2368 SLOGE("Error opening real_blkdev %s for inplace encrypt\n",
2369 real_blkdev);
2370 goto errout;
2371 }
2372 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY)) < 0) {
2373 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n",
2374 crypto_blkdev);
2375 goto errout;
2376 }
2377
2378 f2fs_info = generate_f2fs_info(data.realfd);
2379 if (!f2fs_info)
2380 goto errout;
2381
2382 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2383 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2384 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2385
2386 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2387
2388 data.one_pct = data.tot_used_blocks / 100;
2389 data.cur_pct = 0;
2390 data.time_started = time(NULL);
2391 data.remaining_time = -1;
2392
2393 data.buffer = malloc(f2fs_info->block_size);
2394 if (!data.buffer) {
2395 SLOGE("Failed to allocate crypto buffer");
2396 goto errout;
2397 }
2398
2399 data.count = 0;
2400
2401 /* Currently, this either runs to completion, or hits a nonrecoverable error */
2402 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2403
2404 if (rc) {
2405 SLOGE("Error in running over blocks");
2406 goto errout;
2407 }
2408
2409 *size_already_done += size;
2410 rc = 0;
2411
2412errout:
2413 if (rc)
2414 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2415
2416 free(f2fs_info);
2417 free(data.buffer);
2418 close(data.realfd);
2419 close(data.cryptofd);
2420
2421 return rc;
2422}
2423
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002424static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2425 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002426 off64_t tot_size,
2427 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002428{
2429 int realfd, cryptofd;
2430 char *buf[CRYPT_INPLACE_BUFSIZE];
2431 int rc = -1;
2432 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002433 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002434 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002435
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002436 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
2437 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
2438 return -1;
2439 }
2440
2441 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
2442 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
2443 close(realfd);
2444 return -1;
2445 }
2446
2447 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2448 * The size passed in is the number of 512 byte sectors in the filesystem.
2449 * So compute the number of whole 4K blocks we should read/write,
2450 * and the remainder.
2451 */
2452 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2453 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002454 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2455 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002456
2457 SLOGE("Encrypting filesystem in place...");
2458
Paul Lawrence87999172014-02-20 12:21:31 -08002459 i = previously_encrypted_upto + 1 - *size_already_done;
2460
2461 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2462 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2463 goto errout;
2464 }
2465
2466 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2467 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2468 goto errout;
2469 }
2470
2471 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2472 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2473 SLOGE("Error reading initial sectors from real_blkdev %s for "
2474 "inplace encrypt\n", crypto_blkdev);
2475 goto errout;
2476 }
2477 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2478 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2479 "inplace encrypt\n", crypto_blkdev);
2480 goto errout;
2481 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002482 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002483 }
2484 }
2485
Ken Sumrall29d8da82011-05-18 17:20:07 -07002486 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002487 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002488 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002489 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002490 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002491 if (new_pct > cur_pct) {
2492 char buf[8];
2493
2494 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002495 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002496 property_set("vold.encrypt_progress", buf);
2497 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002498 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002499 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002500 goto errout;
2501 }
2502 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002503 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2504 goto errout;
2505 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002506 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002507 CRYPT_SECTORS_PER_BUFSIZE,
2508 i * CRYPT_SECTORS_PER_BUFSIZE);
2509 }
2510
Paul Lawrence73d7a022014-06-09 14:10:09 -07002511 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002512 SLOGE("Stopping encryption due to low battery");
2513 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2514 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002515 goto errout;
2516 }
2517 }
2518
2519 /* Do any remaining sectors */
2520 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002521 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2522 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002523 goto errout;
2524 }
Paul Lawrence87999172014-02-20 12:21:31 -08002525 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2526 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002527 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002528 } else {
2529 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002530 }
2531 }
2532
Ken Sumrall29d8da82011-05-18 17:20:07 -07002533 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002534 rc = 0;
2535
2536errout:
2537 close(realfd);
2538 close(cryptofd);
2539
2540 return rc;
2541}
2542
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002543static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2544 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002545 off64_t tot_size,
2546 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002547{
Paul Lawrence87999172014-02-20 12:21:31 -08002548 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002549 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002550 }
2551
2552 if (*size_already_done + size < previously_encrypted_upto) {
2553 *size_already_done += size;
2554 return 0;
2555 }
2556
Daniel Rosenberge82df162014-08-15 22:19:23 +00002557 /* TODO: identify filesystem type.
2558 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2559 * then we will drop down to cryptfs_enable_inplace_f2fs.
2560 * */
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002561 if (cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002562 size, size_already_done,
2563 tot_size, previously_encrypted_upto) == 0) {
2564 return 0;
2565 }
2566
2567 if (cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
2568 size, size_already_done,
2569 tot_size, previously_encrypted_upto) == 0) {
2570 return 0;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002571 }
2572
2573 return cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002574 size, size_already_done, tot_size,
2575 previously_encrypted_upto);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002576}
2577
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002578#define CRYPTO_ENABLE_WIPE 1
2579#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002580
2581#define FRAMEWORK_BOOT_WAIT 60
2582
Ken Sumrall29d8da82011-05-18 17:20:07 -07002583static inline int should_encrypt(struct volume_info *volume)
2584{
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002585 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
Ken Sumrall29d8da82011-05-18 17:20:07 -07002586 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
2587}
2588
Paul Lawrence87999172014-02-20 12:21:31 -08002589static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2590{
2591 int fd = open(filename, O_RDONLY);
2592 if (fd == -1) {
2593 SLOGE("Error opening file %s", filename);
2594 return -1;
2595 }
2596
2597 char block[CRYPT_INPLACE_BUFSIZE];
2598 memset(block, 0, sizeof(block));
2599 if (unix_read(fd, block, sizeof(block)) < 0) {
2600 SLOGE("Error reading file %s", filename);
2601 close(fd);
2602 return -1;
2603 }
2604
2605 close(fd);
2606
2607 SHA256_CTX c;
2608 SHA256_Init(&c);
2609 SHA256_Update(&c, block, sizeof(block));
2610 SHA256_Final(buf, &c);
2611
2612 return 0;
2613}
2614
JP Abgrall62c7af32014-06-16 13:01:23 -07002615static int get_fs_type(struct fstab_rec *rec)
2616{
2617 if (!strcmp(rec->fs_type, "ext4")) {
2618 return EXT4_FS;
2619 } else if (!strcmp(rec->fs_type, "f2fs")) {
2620 return F2FS_FS;
2621 } else {
2622 return -1;
2623 }
2624}
2625
Paul Lawrence87999172014-02-20 12:21:31 -08002626static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2627 char *crypto_blkdev, char *real_blkdev,
2628 int previously_encrypted_upto)
2629{
2630 off64_t cur_encryption_done=0, tot_encryption_size=0;
2631 int i, rc = -1;
2632
Paul Lawrence73d7a022014-06-09 14:10:09 -07002633 if (!is_battery_ok_to_start()) {
2634 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002635 return 0;
2636 }
2637
2638 /* The size of the userdata partition, and add in the vold volumes below */
2639 tot_encryption_size = crypt_ftr->fs_size;
2640
2641 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002642 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2643 int fs_type = get_fs_type(rec);
2644 if (fs_type < 0) {
2645 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2646 return -1;
2647 }
2648 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002649 } else if (how == CRYPTO_ENABLE_INPLACE) {
2650 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2651 crypt_ftr->fs_size, &cur_encryption_done,
2652 tot_encryption_size,
2653 previously_encrypted_upto);
2654
Paul Lawrence73d7a022014-06-09 14:10:09 -07002655 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002656 crypt_ftr->encrypted_upto = cur_encryption_done;
2657 }
2658
Paul Lawrence73d7a022014-06-09 14:10:09 -07002659 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002660 /* The inplace routine never actually sets the progress to 100% due
2661 * to the round down nature of integer division, so set it here */
2662 property_set("vold.encrypt_progress", "100");
2663 }
2664 } else {
2665 /* Shouldn't happen */
2666 SLOGE("cryptfs_enable: internal error, unknown option\n");
2667 rc = -1;
2668 }
2669
2670 return rc;
2671}
2672
Paul Lawrence13486032014-02-03 13:28:11 -08002673int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
2674 int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002675{
2676 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002677 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07002678 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002679 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07002680 int rc=-1, fd, i, ret;
Paul Lawrence87999172014-02-20 12:21:31 -08002681 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002682 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002683 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002684 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002685 char key_loc[PROPERTY_VALUE_MAX];
2686 char fuse_sdcard[PROPERTY_VALUE_MAX];
2687 char *sd_mnt_point;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002688 int num_vols;
2689 struct volume_info *vol_list = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002690 off64_t previously_encrypted_upto = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002691
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002692 if (!strcmp(howarg, "wipe")) {
2693 how = CRYPTO_ENABLE_WIPE;
2694 } else if (! strcmp(howarg, "inplace")) {
2695 how = CRYPTO_ENABLE_INPLACE;
2696 } else {
2697 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002698 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002699 }
2700
Paul Lawrence87999172014-02-20 12:21:31 -08002701 /* See if an encryption was underway and interrupted */
2702 if (how == CRYPTO_ENABLE_INPLACE
2703 && get_crypt_ftr_and_key(&crypt_ftr) == 0
2704 && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
2705 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2706 crypt_ftr.encrypted_upto = 0;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002707 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
2708
2709 /* At this point, we are in an inconsistent state. Until we successfully
2710 complete encryption, a reboot will leave us broken. So mark the
2711 encryption failed in case that happens.
2712 On successfully completing encryption, remove this flag */
2713 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2714
2715 put_crypt_ftr_and_key(&crypt_ftr);
Paul Lawrence87999172014-02-20 12:21:31 -08002716 }
2717
2718 property_get("ro.crypto.state", encrypted_state, "");
2719 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2720 SLOGE("Device is already running encrypted, aborting");
2721 goto error_unencrypted;
2722 }
2723
2724 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2725 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002726 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002727
Ken Sumrall3ed82362011-01-28 23:31:16 -08002728 /* Get the size of the real block device */
2729 fd = open(real_blkdev, O_RDONLY);
2730 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
2731 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2732 goto error_unencrypted;
2733 }
2734 close(fd);
2735
2736 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002737 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002738 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002739 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002740 if (fs_size_sec == 0)
2741 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2742
Paul Lawrence87999172014-02-20 12:21:31 -08002743 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002744
2745 if (fs_size_sec > max_fs_size_sec) {
2746 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2747 goto error_unencrypted;
2748 }
2749 }
2750
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002751 /* Get a wakelock as this may take a while, and we don't want the
2752 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2753 * wants to keep the screen on, it can grab a full wakelock.
2754 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002755 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002756 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2757
Jeff Sharkey7382f812012-08-23 14:08:59 -07002758 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07002759 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07002760 if (!sd_mnt_point) {
2761 sd_mnt_point = getenv("EXTERNAL_STORAGE");
2762 }
2763 if (!sd_mnt_point) {
2764 sd_mnt_point = "/mnt/sdcard";
2765 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07002766
Paul Lawrence87999172014-02-20 12:21:31 -08002767 /* TODO
2768 * Currently do not have test devices with multiple encryptable volumes.
2769 * When we acquire some, re-add support.
2770 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002771 num_vols=vold_getNumDirectVolumes();
2772 vol_list = malloc(sizeof(struct volume_info) * num_vols);
2773 vold_getDirectVolumeList(vol_list);
2774
2775 for (i=0; i<num_vols; i++) {
2776 if (should_encrypt(&vol_list[i])) {
Paul Lawrence87999172014-02-20 12:21:31 -08002777 SLOGE("Cannot encrypt if there are multiple encryptable volumes"
2778 "%s\n", vol_list[i].label);
2779 goto error_unencrypted;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002780 }
2781 }
2782
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002783 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002784 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002785 */
2786 property_set("vold.decrypt", "trigger_shutdown_framework");
2787 SLOGD("Just asked init to shut down class main\n");
2788
Ken Sumrall425524d2012-06-14 20:55:28 -07002789 if (vold_unmountAllAsecs()) {
2790 /* Just report the error. If any are left mounted,
2791 * umounting /data below will fail and handle the error.
2792 */
2793 SLOGE("Error unmounting internal asecs");
2794 }
2795
Ken Sumrall29d8da82011-05-18 17:20:07 -07002796 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
2797 if (!strcmp(fuse_sdcard, "true")) {
2798 /* This is a device using the fuse layer to emulate the sdcard semantics
2799 * on top of the userdata partition. vold does not manage it, it is managed
2800 * by the sdcard service. The sdcard service was killed by the property trigger
2801 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
2802 * unlike the case for vold managed devices above.
2803 */
2804 if (wait_and_unmount(sd_mnt_point)) {
2805 goto error_shutting_down;
2806 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002807 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002808
2809 /* Now unmount the /data partition. */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002810 if (wait_and_unmount(DATA_MNT_POINT)) {
JP Abgrall502dc742013-11-01 13:06:20 -07002811 if (allow_reboot) {
2812 goto error_shutting_down;
2813 } else {
2814 goto error_unencrypted;
2815 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002816 }
2817
2818 /* Do extra work for a better UX when doing the long inplace encryption */
2819 if (how == CRYPTO_ENABLE_INPLACE) {
2820 /* Now that /data is unmounted, we need to mount a tmpfs
2821 * /data, set a property saying we're doing inplace encryption,
2822 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002823 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002824 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002825 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002826 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002827 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002828 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002829
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002830 /* restart the framework. */
2831 /* Create necessary paths on /data */
2832 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002833 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002834 }
2835
Ken Sumrall92736ef2012-10-17 20:57:14 -07002836 /* Ugh, shutting down the framework is not synchronous, so until it
2837 * can be fixed, this horrible hack will wait a moment for it all to
2838 * shut down before proceeding. Without it, some devices cannot
2839 * restart the graphics services.
2840 */
2841 sleep(2);
2842
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002843 /* startup service classes main and late_start */
2844 property_set("vold.decrypt", "trigger_restart_min_framework");
2845 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002846
Ken Sumrall7df84122011-01-18 14:04:08 -08002847 /* OK, the framework is restarted and will soon be showing a
2848 * progress bar. Time to setup an encrypted mapping, and
2849 * either write a new filesystem, or encrypt in place updating
2850 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002851 */
2852 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002853
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002854 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002855 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence87999172014-02-20 12:21:31 -08002856 if (previously_encrypted_upto == 0) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002857 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2858 goto error_shutting_down;
2859 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002860
Paul Lawrence87999172014-02-20 12:21:31 -08002861 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2862 crypt_ftr.fs_size = nr_sec
2863 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2864 } else {
2865 crypt_ftr.fs_size = nr_sec;
2866 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002867 /* At this point, we are in an inconsistent state. Until we successfully
2868 complete encryption, a reboot will leave us broken. So mark the
2869 encryption failed in case that happens.
2870 On successfully completing encryption, remove this flag */
2871 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence87999172014-02-20 12:21:31 -08002872 crypt_ftr.crypt_type = crypt_type;
2873 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002874
Paul Lawrence87999172014-02-20 12:21:31 -08002875 /* Make an encrypted master key */
2876 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
2877 SLOGE("Cannot create encrypted master key\n");
2878 goto error_shutting_down;
2879 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002880
Paul Lawrence87999172014-02-20 12:21:31 -08002881 /* Write the key to the end of the partition */
2882 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002883
Paul Lawrence87999172014-02-20 12:21:31 -08002884 /* If any persistent data has been remembered, save it.
2885 * If none, create a valid empty table and save that.
2886 */
2887 if (!persist_data) {
2888 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
2889 if (pdata) {
2890 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2891 persist_data = pdata;
2892 }
2893 }
2894 if (persist_data) {
2895 save_persistent_data();
2896 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002897 }
2898
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002899 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002900 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
2901 "userdata");
2902
Paul Lawrence87999172014-02-20 12:21:31 -08002903 /* If we are continuing, check checksums match */
2904 rc = 0;
2905 if (previously_encrypted_upto) {
2906 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2907 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002908
Paul Lawrence87999172014-02-20 12:21:31 -08002909 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2910 sizeof(hash_first_block)) != 0) {
2911 SLOGE("Checksums do not match - trigger wipe");
2912 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002913 }
2914 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002915
Paul Lawrence87999172014-02-20 12:21:31 -08002916 if (!rc) {
2917 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
2918 crypto_blkdev, real_blkdev,
2919 previously_encrypted_upto);
2920 }
2921
2922 /* Calculate checksum if we are not finished */
Paul Lawrence73d7a022014-06-09 14:10:09 -07002923 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002924 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2925 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002926 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002927 SLOGE("Error calculating checksum for continuing encryption");
2928 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002929 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002930 }
2931
2932 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002933 delete_crypto_blk_dev("userdata");
Ken Sumrall29d8da82011-05-18 17:20:07 -07002934
2935 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002936
2937 if (! rc) {
2938 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002939 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002940
Paul Lawrence6bfed202014-07-28 12:47:22 -07002941 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002942 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2943 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002944 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002945 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002946
Paul Lawrence6bfed202014-07-28 12:47:22 -07002947 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002948
Paul Lawrence73d7a022014-06-09 14:10:09 -07002949 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002950 char value[PROPERTY_VALUE_MAX];
2951 property_get("ro.crypto.state", value, "");
2952 if (!strcmp(value, "")) {
2953 /* default encryption - continue first boot sequence */
2954 property_set("ro.crypto.state", "encrypted");
2955 release_wake_lock(lockid);
2956 cryptfs_check_passwd(DEFAULT_PASSWORD);
2957 cryptfs_restart_internal(1);
2958 return 0;
2959 } else {
2960 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08002961 cryptfs_reboot(reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002962 }
Paul Lawrence87999172014-02-20 12:21:31 -08002963 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002964 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Paul Lawrence87999172014-02-20 12:21:31 -08002965 cryptfs_reboot(shutdown);
2966 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002967 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002968 char value[PROPERTY_VALUE_MAX];
2969
Ken Sumrall319369a2012-06-27 16:30:18 -07002970 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002971 if (!strcmp(value, "1")) {
2972 /* wipe data if encryption failed */
2973 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
2974 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07002975 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002976 if (fd >= 0) {
2977 write(fd, "--wipe_data", strlen("--wipe_data") + 1);
2978 close(fd);
2979 } else {
2980 SLOGE("could not open /cache/recovery/command\n");
2981 }
Paul Lawrence87999172014-02-20 12:21:31 -08002982 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002983 } else {
2984 /* set property to trigger dialog */
2985 property_set("vold.encrypt_progress", "error_partially_encrypted");
2986 release_wake_lock(lockid);
2987 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002988 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002989 }
2990
Ken Sumrall3ed82362011-01-28 23:31:16 -08002991 /* hrm, the encrypt step claims success, but the reboot failed.
2992 * This should not happen.
2993 * Set the property and return. Hope the framework can deal with it.
2994 */
2995 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002996 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002997 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002998
2999error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07003000 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003001 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003002 if (lockid[0]) {
3003 release_wake_lock(lockid);
3004 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003005 return -1;
3006
3007error_shutting_down:
3008 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3009 * but the framework is stopped and not restarted to show the error, so it's up to
3010 * vold to restart the system.
3011 */
3012 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08003013 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003014
3015 /* shouldn't get here */
3016 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003017 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003018 if (lockid[0]) {
3019 release_wake_lock(lockid);
3020 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003021 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003022}
3023
Paul Lawrence45f10532014-04-04 18:11:56 +00003024int cryptfs_enable(char *howarg, int type, char *passwd, int allow_reboot)
Paul Lawrence13486032014-02-03 13:28:11 -08003025{
Paul Lawrence45f10532014-04-04 18:11:56 +00003026 return cryptfs_enable_internal(howarg, type, passwd, allow_reboot);
Paul Lawrence13486032014-02-03 13:28:11 -08003027}
3028
3029int cryptfs_enable_default(char *howarg, int allow_reboot)
3030{
3031 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
3032 DEFAULT_PASSWORD, allow_reboot);
3033}
3034
3035int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003036{
3037 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003038 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003039
3040 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003041 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003042 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003043 return -1;
3044 }
3045
Paul Lawrencef4faa572014-01-29 13:31:03 -08003046 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3047 SLOGE("Invalid crypt_type %d", crypt_type);
3048 return -1;
3049 }
3050
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003051 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003052 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003053 SLOGE("Error getting crypt footer and key");
3054 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003055 }
3056
Paul Lawrencef4faa572014-01-29 13:31:03 -08003057 crypt_ftr.crypt_type = crypt_type;
3058
3059 encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
3060 : newpw,
3061 crypt_ftr.salt,
3062 saved_master_key,
3063 crypt_ftr.master_key,
3064 &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003065
Jason parks70a4b3f2011-01-28 10:10:47 -06003066 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003067 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003068
3069 return 0;
3070}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003071
3072static int persist_get_key(char *fieldname, char *value)
3073{
3074 unsigned int i;
3075
3076 if (persist_data == NULL) {
3077 return -1;
3078 }
3079 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3080 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3081 /* We found it! */
3082 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3083 return 0;
3084 }
3085 }
3086
3087 return -1;
3088}
3089
3090static int persist_set_key(char *fieldname, char *value, int encrypted)
3091{
3092 unsigned int i;
3093 unsigned int num;
3094 struct crypt_mnt_ftr crypt_ftr;
3095 unsigned int max_persistent_entries;
3096 unsigned int dsize;
3097
3098 if (persist_data == NULL) {
3099 return -1;
3100 }
3101
3102 /* If encrypted, use the values from the crypt_ftr, otherwise
3103 * use the values for the current spec.
3104 */
3105 if (encrypted) {
3106 if(get_crypt_ftr_and_key(&crypt_ftr)) {
3107 return -1;
3108 }
3109 dsize = crypt_ftr.persist_data_size;
3110 } else {
3111 dsize = CRYPT_PERSIST_DATA_SIZE;
3112 }
3113 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3114 sizeof(struct crypt_persist_entry);
3115
3116 num = persist_data->persist_valid_entries;
3117
3118 for (i = 0; i < num; i++) {
3119 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3120 /* We found an existing entry, update it! */
3121 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3122 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3123 return 0;
3124 }
3125 }
3126
3127 /* We didn't find it, add it to the end, if there is room */
3128 if (persist_data->persist_valid_entries < max_persistent_entries) {
3129 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3130 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3131 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3132 persist_data->persist_valid_entries++;
3133 return 0;
3134 }
3135
3136 return -1;
3137}
3138
3139/* Return the value of the specified field. */
3140int cryptfs_getfield(char *fieldname, char *value, int len)
3141{
3142 char temp_value[PROPERTY_VALUE_MAX];
3143 char real_blkdev[MAXPATHLEN];
3144 /* 0 is success, 1 is not encrypted,
3145 * -1 is value not set, -2 is any other error
3146 */
3147 int rc = -2;
3148
3149 if (persist_data == NULL) {
3150 load_persistent_data();
3151 if (persist_data == NULL) {
3152 SLOGE("Getfield error, cannot load persistent data");
3153 goto out;
3154 }
3155 }
3156
3157 if (!persist_get_key(fieldname, temp_value)) {
3158 /* We found it, copy it to the caller's buffer and return */
3159 strlcpy(value, temp_value, len);
3160 rc = 0;
3161 } else {
3162 /* Sadness, it's not there. Return the error */
3163 rc = -1;
3164 }
3165
3166out:
3167 return rc;
3168}
3169
3170/* Set the value of the specified field. */
3171int cryptfs_setfield(char *fieldname, char *value)
3172{
3173 struct crypt_persist_data stored_pdata;
3174 struct crypt_persist_data *pdata_p;
3175 struct crypt_mnt_ftr crypt_ftr;
3176 char encrypted_state[PROPERTY_VALUE_MAX];
3177 /* 0 is success, -1 is an error */
3178 int rc = -1;
3179 int encrypted = 0;
3180
3181 if (persist_data == NULL) {
3182 load_persistent_data();
3183 if (persist_data == NULL) {
3184 SLOGE("Setfield error, cannot load persistent data");
3185 goto out;
3186 }
3187 }
3188
3189 property_get("ro.crypto.state", encrypted_state, "");
3190 if (!strcmp(encrypted_state, "encrypted") ) {
3191 encrypted = 1;
3192 }
3193
3194 if (persist_set_key(fieldname, value, encrypted)) {
3195 goto out;
3196 }
3197
3198 /* If we are running encrypted, save the persistent data now */
3199 if (encrypted) {
3200 if (save_persistent_data()) {
3201 SLOGE("Setfield error, cannot save persistent data");
3202 goto out;
3203 }
3204 }
3205
3206 rc = 0;
3207
3208out:
3209 return rc;
3210}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003211
3212/* Checks userdata. Attempt to mount the volume if default-
3213 * encrypted.
3214 * On success trigger next init phase and return 0.
3215 * Currently do not handle failure - see TODO below.
3216 */
3217int cryptfs_mount_default_encrypted(void)
3218{
3219 char decrypt_state[PROPERTY_VALUE_MAX];
3220 property_get("vold.decrypt", decrypt_state, "0");
3221 if (!strcmp(decrypt_state, "0")) {
3222 SLOGE("Not encrypted - should not call here");
3223 } else {
3224 int crypt_type = cryptfs_get_password_type();
3225 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3226 SLOGE("Bad crypt type - error");
3227 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3228 SLOGD("Password is not default - "
3229 "starting min framework to prompt");
3230 property_set("vold.decrypt", "trigger_restart_min_framework");
3231 return 0;
3232 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3233 SLOGD("Password is default - restarting filesystem");
3234 cryptfs_restart_internal(0);
3235 return 0;
3236 } else {
3237 SLOGE("Encrypted, default crypt type but can't decrypt");
3238 }
3239 }
3240
Paul Lawrence6bfed202014-07-28 12:47:22 -07003241 /** Corrupt. Allow us to boot into framework, which will detect bad
3242 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003243 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003244 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003245 return 0;
3246}
3247
3248/* Returns type of the password, default, pattern, pin or password.
3249 */
3250int cryptfs_get_password_type(void)
3251{
3252 struct crypt_mnt_ftr crypt_ftr;
3253
3254 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3255 SLOGE("Error getting crypt footer and key\n");
3256 return -1;
3257 }
3258
Paul Lawrence6bfed202014-07-28 12:47:22 -07003259 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3260 return -1;
3261 }
3262
Paul Lawrencef4faa572014-01-29 13:31:03 -08003263 return crypt_ftr.crypt_type;
3264}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003265
Paul Lawrence399317e2014-03-10 13:20:50 -07003266char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003267{
Paul Lawrence399317e2014-03-10 13:20:50 -07003268 struct timespec now;
3269 clock_gettime(CLOCK_MONOTONIC, &now);
3270 if (now.tv_sec < password_expiry_time) {
3271 return password;
3272 } else {
3273 cryptfs_clear_password();
3274 return 0;
3275 }
3276}
3277
3278void cryptfs_clear_password()
3279{
3280 if (password) {
3281 size_t len = strlen(password);
3282 memset(password, 0, len);
3283 free(password);
3284 password = 0;
3285 password_expiry_time = 0;
3286 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003287}