blob: dee6bacb19e7990f8e3db15a72c0370f78593c6c [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>
Adam Langley41405bb2015-01-22 16:45:28 -080039#include <openssl/sha.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080040#include <errno.h>
Ken Sumrall3ed82362011-01-28 23:31:16 -080041#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070042#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070043#include <fs_mgr.h>
Paul Lawrence9c58a872014-09-30 09:12:51 -070044#include <time.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080045#include "cryptfs.h"
46#define LOG_TAG "Cryptfs"
47#include "cutils/log.h"
48#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070049#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080050#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070051#include <logwrap/logwrap.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070052#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070053#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070054#include "crypto_scrypt.h"
Paul Lawrenceae59fe62014-01-21 08:23:27 -080055#include "ext4_utils.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000056#include "f2fs_sparseblock.h"
Paul Lawrence87999172014-02-20 12:21:31 -080057#include "CheckBattery.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080058#include "Process.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080059
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070060#include <hardware/keymaster.h>
61
Mark Salyzyn3e971272014-01-21 13:27:04 -080062#define UNUSED __attribute__((unused))
63
Mark Salyzyn5eecc442014-02-12 14:16:14 -080064#define UNUSED __attribute__((unused))
65
Ken Sumrall8f869aa2010-12-03 03:47:09 -080066#define DM_CRYPT_BUF_SIZE 4096
67
Jason parks70a4b3f2011-01-28 10:10:47 -060068#define HASH_COUNT 2000
69#define KEY_LEN_BYTES 16
70#define IV_LEN_BYTES 16
71
Ken Sumrall29d8da82011-05-18 17:20:07 -070072#define KEY_IN_FOOTER "footer"
73
Paul Lawrencef4faa572014-01-29 13:31:03 -080074// "default_password" encoded into hex (d=0x64 etc)
75#define DEFAULT_PASSWORD "64656661756c745f70617373776f7264"
76
Ken Sumrall29d8da82011-05-18 17:20:07 -070077#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070078#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070079
Ken Sumralle919efe2012-09-29 17:07:41 -070080#define TABLE_LOAD_RETRIES 10
81
Shawn Willden47ba10d2014-09-03 17:07:06 -060082#define RSA_KEY_SIZE 2048
83#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
84#define RSA_EXPONENT 0x10001
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070085
Paul Lawrence8e3f4512014-09-08 10:11:17 -070086#define RETRY_MOUNT_ATTEMPTS 10
87#define RETRY_MOUNT_DELAY_SECONDS 1
88
Ken Sumrall8f869aa2010-12-03 03:47:09 -080089char *me = "cryptfs";
90
Jason parks70a4b3f2011-01-28 10:10:47 -060091static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070092static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060093static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -070094static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -080095
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070096static int keymaster_init(keymaster_device_t **keymaster_dev)
97{
98 int rc;
99
100 const hw_module_t* mod;
101 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
102 if (rc) {
103 ALOGE("could not find any keystore module");
104 goto out;
105 }
106
107 rc = keymaster_open(mod, keymaster_dev);
108 if (rc) {
109 ALOGE("could not open keymaster device in %s (%s)",
110 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
111 goto out;
112 }
113
114 return 0;
115
116out:
117 *keymaster_dev = NULL;
118 return rc;
119}
120
121/* Should we use keymaster? */
122static int keymaster_check_compatibility()
123{
124 keymaster_device_t *keymaster_dev = 0;
125 int rc = 0;
126
127 if (keymaster_init(&keymaster_dev)) {
128 SLOGE("Failed to init keymaster");
129 rc = -1;
130 goto out;
131 }
132
Paul Lawrence8c008392014-05-06 14:02:48 -0700133 SLOGI("keymaster version is %d", keymaster_dev->common.module->module_api_version);
134
135 if (keymaster_dev->common.module->module_api_version
136 < KEYMASTER_MODULE_API_VERSION_0_3) {
137 rc = 0;
138 goto out;
139 }
140
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700141 if (keymaster_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE) {
142 rc = 1;
143 }
144
145out:
146 keymaster_close(keymaster_dev);
147 return rc;
148}
149
150/* Create a new keymaster key and store it in this footer */
151static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
152{
153 uint8_t* key = 0;
154 keymaster_device_t *keymaster_dev = 0;
155
156 if (keymaster_init(&keymaster_dev)) {
157 SLOGE("Failed to init keymaster");
158 return -1;
159 }
160
161 int rc = 0;
162
163 keymaster_rsa_keygen_params_t params;
164 memset(&params, '\0', sizeof(params));
Shawn Willden47ba10d2014-09-03 17:07:06 -0600165 params.public_exponent = RSA_EXPONENT;
166 params.modulus_size = RSA_KEY_SIZE;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700167
168 size_t key_size;
169 if (keymaster_dev->generate_keypair(keymaster_dev, TYPE_RSA, &params,
170 &key, &key_size)) {
171 SLOGE("Failed to generate keypair");
172 rc = -1;
173 goto out;
174 }
175
176 if (key_size > KEYMASTER_BLOB_SIZE) {
177 SLOGE("Keymaster key too large for crypto footer");
178 rc = -1;
179 goto out;
180 }
181
182 memcpy(ftr->keymaster_blob, key, key_size);
183 ftr->keymaster_blob_size = key_size;
184
185out:
186 keymaster_close(keymaster_dev);
187 free(key);
188 return rc;
189}
190
Shawn Willdene17a9c42014-09-08 13:04:08 -0600191/* This signs the given object using the keymaster key. */
192static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600193 const unsigned char *object,
194 const size_t object_size,
195 unsigned char **signature,
196 size_t *signature_size)
197{
198 int rc = 0;
199 keymaster_device_t *keymaster_dev = 0;
200 if (keymaster_init(&keymaster_dev)) {
201 SLOGE("Failed to init keymaster");
202 return -1;
203 }
204
205 /* We currently set the digest type to DIGEST_NONE because it's the
206 * only supported value for keymaster. A similar issue exists with
207 * PADDING_NONE. Long term both of these should likely change.
208 */
209 keymaster_rsa_sign_params_t params;
210 params.digest_type = DIGEST_NONE;
211 params.padding_type = PADDING_NONE;
212
213 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600214 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600215 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600216
Shawn Willdene17a9c42014-09-08 13:04:08 -0600217 // To sign a message with RSA, the message must satisfy two
218 // constraints:
219 //
220 // 1. The message, when interpreted as a big-endian numeric value, must
221 // be strictly less than the public modulus of the RSA key. Note
222 // that because the most significant bit of the public modulus is
223 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
224 // key), an n-bit message with most significant bit 0 always
225 // satisfies this requirement.
226 //
227 // 2. The message must have the same length in bits as the public
228 // modulus of the RSA key. This requirement isn't mathematically
229 // necessary, but is necessary to ensure consistency in
230 // implementations.
231 switch (ftr->kdf_type) {
232 case KDF_SCRYPT_KEYMASTER_UNPADDED:
233 // This is broken: It produces a message which is shorter than
234 // the public modulus, failing criterion 2.
235 memcpy(to_sign, object, object_size);
236 to_sign_size = object_size;
237 SLOGI("Signing unpadded object");
238 break;
239 case KDF_SCRYPT_KEYMASTER_BADLY_PADDED:
240 // This is broken: Since the value of object is uniformly
241 // distributed, it produces a message that is larger than the
242 // public modulus with probability 0.25.
243 memcpy(to_sign, object, min(RSA_KEY_SIZE_BYTES, object_size));
244 SLOGI("Signing end-padded object");
245 break;
246 case KDF_SCRYPT_KEYMASTER:
247 // This ensures the most significant byte of the signed message
248 // is zero. We could have zero-padded to the left instead, but
249 // this approach is slightly more robust against changes in
250 // object size. However, it's still broken (but not unusably
251 // so) because we really should be using a proper RSA padding
252 // function, such as OAEP.
253 //
254 // TODO(paullawrence): When keymaster 0.4 is available, change
255 // this to use the padding options it provides.
256 memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
257 SLOGI("Signing safely-padded object");
258 break;
259 default:
260 SLOGE("Unknown KDF type %d", ftr->kdf_type);
261 return -1;
262 }
263
Shawn Willden47ba10d2014-09-03 17:07:06 -0600264 rc = keymaster_dev->sign_data(keymaster_dev,
265 &params,
266 ftr->keymaster_blob,
267 ftr->keymaster_blob_size,
268 to_sign,
Shawn Willdene17a9c42014-09-08 13:04:08 -0600269 to_sign_size,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600270 signature,
271 signature_size);
272
273 keymaster_close(keymaster_dev);
274 return rc;
275}
276
Paul Lawrence399317e2014-03-10 13:20:50 -0700277/* Store password when userdata is successfully decrypted and mounted.
278 * Cleared by cryptfs_clear_password
279 *
280 * To avoid a double prompt at boot, we need to store the CryptKeeper
281 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
282 * Since the entire framework is torn down and rebuilt after encryption,
283 * we have to use a daemon or similar to store the password. Since vold
284 * is secured against IPC except from system processes, it seems a reasonable
285 * place to store this.
286 *
287 * password should be cleared once it has been used.
288 *
289 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800290 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700291static char* password = 0;
292static int password_expiry_time = 0;
293static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800294
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800295extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800296
Paul Lawrence87999172014-02-20 12:21:31 -0800297enum RebootType {reboot, recovery, shutdown};
298static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700299{
Paul Lawrence87999172014-02-20 12:21:31 -0800300 switch(rt) {
301 case reboot:
302 property_set(ANDROID_RB_PROPERTY, "reboot");
303 break;
304
305 case recovery:
306 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
307 break;
308
309 case shutdown:
310 property_set(ANDROID_RB_PROPERTY, "shutdown");
311 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700312 }
Paul Lawrence87999172014-02-20 12:21:31 -0800313
Ken Sumralladfba362013-06-04 16:37:52 -0700314 sleep(20);
315
316 /* Shouldn't get here, reboot should happen before sleep times out */
317 return;
318}
319
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800320static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
321{
322 memset(io, 0, dataSize);
323 io->data_size = dataSize;
324 io->data_start = sizeof(struct dm_ioctl);
325 io->version[0] = 4;
326 io->version[1] = 0;
327 io->version[2] = 0;
328 io->flags = flags;
329 if (name) {
330 strncpy(io->name, name, sizeof(io->name));
331 }
332}
333
Kenny Rootc4c70f12013-06-14 12:11:38 -0700334/**
335 * Gets the default device scrypt parameters for key derivation time tuning.
336 * The parameters should lead to about one second derivation time for the
337 * given device.
338 */
339static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
340 const int default_params[] = SCRYPT_DEFAULTS;
341 int params[] = SCRYPT_DEFAULTS;
342 char paramstr[PROPERTY_VALUE_MAX];
343 char *token;
344 char *saveptr;
345 int i;
346
347 property_get(SCRYPT_PROP, paramstr, "");
348 if (paramstr[0] != '\0') {
349 /*
350 * The token we're looking for should be three integers separated by
351 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
352 */
Kenny Root2947e342013-08-14 15:54:49 -0700353 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
354 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700355 i++, token = strtok_r(NULL, ":", &saveptr)) {
356 char *endptr;
357 params[i] = strtol(token, &endptr, 10);
358
359 /*
360 * Check that there was a valid number and it's 8-bit. If not,
361 * break out and the end check will take the default values.
362 */
363 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
364 break;
365 }
366 }
367
368 /*
369 * If there were not enough tokens or a token was malformed (not an
370 * integer), it will end up here and the default parameters can be
371 * taken.
372 */
373 if ((i != 3) || (token != NULL)) {
374 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
375 memcpy(params, default_params, sizeof(params));
376 }
377 }
378
379 ftr->N_factor = params[0];
380 ftr->r_factor = params[1];
381 ftr->p_factor = params[2];
382}
383
Ken Sumrall3ed82362011-01-28 23:31:16 -0800384static unsigned int get_fs_size(char *dev)
385{
386 int fd, block_size;
387 struct ext4_super_block sb;
388 off64_t len;
389
390 if ((fd = open(dev, O_RDONLY)) < 0) {
391 SLOGE("Cannot open device to get filesystem size ");
392 return 0;
393 }
394
395 if (lseek64(fd, 1024, SEEK_SET) < 0) {
396 SLOGE("Cannot seek to superblock");
397 return 0;
398 }
399
400 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
401 SLOGE("Cannot read superblock");
402 return 0;
403 }
404
405 close(fd);
406
Daniel Rosenberge82df162014-08-15 22:19:23 +0000407 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
408 SLOGE("Not a valid ext4 superblock");
409 return 0;
410 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800411 block_size = 1024 << sb.s_log_block_size;
412 /* compute length in bytes */
413 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
414
415 /* return length in sectors */
416 return (unsigned int) (len / 512);
417}
418
Ken Sumrall160b4d62013-04-22 12:15:39 -0700419static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
420{
421 static int cached_data = 0;
422 static off64_t cached_off = 0;
423 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
424 int fd;
425 char key_loc[PROPERTY_VALUE_MAX];
426 char real_blkdev[PROPERTY_VALUE_MAX];
427 unsigned int nr_sec;
428 int rc = -1;
429
430 if (!cached_data) {
431 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
432
433 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
434 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
435 SLOGE("Cannot open real block device %s\n", real_blkdev);
436 return -1;
437 }
438
439 if ((nr_sec = get_blkdev_size(fd))) {
440 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
441 * encryption info footer and key, and plenty of bytes to spare for future
442 * growth.
443 */
444 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
445 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
446 cached_data = 1;
447 } else {
448 SLOGE("Cannot get size of block device %s\n", real_blkdev);
449 }
450 close(fd);
451 } else {
452 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
453 cached_off = 0;
454 cached_data = 1;
455 }
456 }
457
458 if (cached_data) {
459 if (metadata_fname) {
460 *metadata_fname = cached_metadata_fname;
461 }
462 if (off) {
463 *off = cached_off;
464 }
465 rc = 0;
466 }
467
468 return rc;
469}
470
Ken Sumralle8744072011-01-18 22:01:55 -0800471/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800472 * update the failed mount count but not change the key.
473 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700474static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800475{
476 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800477 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700478 /* starting_off is set to the SEEK_SET offset
479 * where the crypto structure starts
480 */
481 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800482 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700483 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700484 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800485
Ken Sumrall160b4d62013-04-22 12:15:39 -0700486 if (get_crypt_ftr_info(&fname, &starting_off)) {
487 SLOGE("Unable to get crypt_ftr_info\n");
488 return -1;
489 }
490 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700491 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700492 return -1;
493 }
Ken Sumralle550f782013-08-20 13:48:23 -0700494 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
495 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700496 return -1;
497 }
498
499 /* Seek to the start of the crypt footer */
500 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
501 SLOGE("Cannot seek to real block device footer\n");
502 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800503 }
504
505 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
506 SLOGE("Cannot write real block device footer\n");
507 goto errout;
508 }
509
Ken Sumrall3be890f2011-09-14 16:53:46 -0700510 fstat(fd, &statbuf);
511 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700512 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700513 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800514 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800515 goto errout;
516 }
517 }
518
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800519 /* Success! */
520 rc = 0;
521
522errout:
523 close(fd);
524 return rc;
525
526}
527
Ken Sumrall160b4d62013-04-22 12:15:39 -0700528static inline int unix_read(int fd, void* buff, int len)
529{
530 return TEMP_FAILURE_RETRY(read(fd, buff, len));
531}
532
533static inline int unix_write(int fd, const void* buff, int len)
534{
535 return TEMP_FAILURE_RETRY(write(fd, buff, len));
536}
537
538static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
539{
540 memset(pdata, 0, len);
541 pdata->persist_magic = PERSIST_DATA_MAGIC;
542 pdata->persist_valid_entries = 0;
543}
544
545/* A routine to update the passed in crypt_ftr to the lastest version.
546 * fd is open read/write on the device that holds the crypto footer and persistent
547 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
548 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
549 */
550static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
551{
Kenny Root7434b312013-06-14 11:29:53 -0700552 int orig_major = crypt_ftr->major_version;
553 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700554
Kenny Root7434b312013-06-14 11:29:53 -0700555 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
556 struct crypt_persist_data *pdata;
557 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700558
Kenny Rootc4c70f12013-06-14 12:11:38 -0700559 SLOGW("upgrading crypto footer to 1.1");
560
Kenny Root7434b312013-06-14 11:29:53 -0700561 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
562 if (pdata == NULL) {
563 SLOGE("Cannot allocate persisent data\n");
564 return;
565 }
566 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
567
568 /* Need to initialize the persistent data area */
569 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
570 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100571 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700572 return;
573 }
574 /* Write all zeros to the first copy, making it invalid */
575 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
576
577 /* Write a valid but empty structure to the second copy */
578 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
579 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
580
581 /* Update the footer */
582 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
583 crypt_ftr->persist_data_offset[0] = pdata_offset;
584 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
585 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100586 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700587 }
588
Paul Lawrencef4faa572014-01-29 13:31:03 -0800589 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700590 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800591 /* But keep the old kdf_type.
592 * It will get updated later to KDF_SCRYPT after the password has been verified.
593 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700594 crypt_ftr->kdf_type = KDF_PBKDF2;
595 get_device_scrypt_params(crypt_ftr);
596 crypt_ftr->minor_version = 2;
597 }
598
Paul Lawrencef4faa572014-01-29 13:31:03 -0800599 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
600 SLOGW("upgrading crypto footer to 1.3");
601 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
602 crypt_ftr->minor_version = 3;
603 }
604
Kenny Root7434b312013-06-14 11:29:53 -0700605 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
606 if (lseek64(fd, offset, SEEK_SET) == -1) {
607 SLOGE("Cannot seek to crypt footer\n");
608 return;
609 }
610 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700611 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700612}
613
614
615static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800616{
617 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800618 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700619 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800620 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700621 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700622 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800623
Ken Sumrall160b4d62013-04-22 12:15:39 -0700624 if (get_crypt_ftr_info(&fname, &starting_off)) {
625 SLOGE("Unable to get crypt_ftr_info\n");
626 return -1;
627 }
628 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700629 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700630 return -1;
631 }
632 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700633 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700634 return -1;
635 }
636
637 /* Make sure it's 16 Kbytes in length */
638 fstat(fd, &statbuf);
639 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
640 SLOGE("footer file %s is not the expected size!\n", fname);
641 goto errout;
642 }
643
644 /* Seek to the start of the crypt footer */
645 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
646 SLOGE("Cannot seek to real block device footer\n");
647 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800648 }
649
650 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
651 SLOGE("Cannot read real block device footer\n");
652 goto errout;
653 }
654
655 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700656 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800657 goto errout;
658 }
659
Kenny Rootc96a5f82013-06-14 12:08:28 -0700660 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
661 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
662 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800663 goto errout;
664 }
665
Kenny Rootc96a5f82013-06-14 12:08:28 -0700666 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
667 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
668 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800669 }
670
Ken Sumrall160b4d62013-04-22 12:15:39 -0700671 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
672 * copy on disk before returning.
673 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700674 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700675 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800676 }
677
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800678 /* Success! */
679 rc = 0;
680
681errout:
682 close(fd);
683 return rc;
684}
685
Ken Sumrall160b4d62013-04-22 12:15:39 -0700686static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
687{
688 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
689 crypt_ftr->persist_data_offset[1]) {
690 SLOGE("Crypt_ftr persist data regions overlap");
691 return -1;
692 }
693
694 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
695 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
696 return -1;
697 }
698
699 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
700 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
701 CRYPT_FOOTER_OFFSET) {
702 SLOGE("Persistent data extends past crypto footer");
703 return -1;
704 }
705
706 return 0;
707}
708
709static int load_persistent_data(void)
710{
711 struct crypt_mnt_ftr crypt_ftr;
712 struct crypt_persist_data *pdata = NULL;
713 char encrypted_state[PROPERTY_VALUE_MAX];
714 char *fname;
715 int found = 0;
716 int fd;
717 int ret;
718 int i;
719
720 if (persist_data) {
721 /* Nothing to do, we've already loaded or initialized it */
722 return 0;
723 }
724
725
726 /* If not encrypted, just allocate an empty table and initialize it */
727 property_get("ro.crypto.state", encrypted_state, "");
728 if (strcmp(encrypted_state, "encrypted") ) {
729 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
730 if (pdata) {
731 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
732 persist_data = pdata;
733 return 0;
734 }
735 return -1;
736 }
737
738 if(get_crypt_ftr_and_key(&crypt_ftr)) {
739 return -1;
740 }
741
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700742 if ((crypt_ftr.major_version < 1)
743 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700744 SLOGE("Crypt_ftr version doesn't support persistent data");
745 return -1;
746 }
747
748 if (get_crypt_ftr_info(&fname, NULL)) {
749 return -1;
750 }
751
752 ret = validate_persistent_data_storage(&crypt_ftr);
753 if (ret) {
754 return -1;
755 }
756
757 fd = open(fname, O_RDONLY);
758 if (fd < 0) {
759 SLOGE("Cannot open %s metadata file", fname);
760 return -1;
761 }
762
763 if (persist_data == NULL) {
764 pdata = malloc(crypt_ftr.persist_data_size);
765 if (pdata == NULL) {
766 SLOGE("Cannot allocate memory for persistent data");
767 goto err;
768 }
769 }
770
771 for (i = 0; i < 2; i++) {
772 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
773 SLOGE("Cannot seek to read persistent data on %s", fname);
774 goto err2;
775 }
776 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
777 SLOGE("Error reading persistent data on iteration %d", i);
778 goto err2;
779 }
780 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
781 found = 1;
782 break;
783 }
784 }
785
786 if (!found) {
787 SLOGI("Could not find valid persistent data, creating");
788 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
789 }
790
791 /* Success */
792 persist_data = pdata;
793 close(fd);
794 return 0;
795
796err2:
797 free(pdata);
798
799err:
800 close(fd);
801 return -1;
802}
803
804static int save_persistent_data(void)
805{
806 struct crypt_mnt_ftr crypt_ftr;
807 struct crypt_persist_data *pdata;
808 char *fname;
809 off64_t write_offset;
810 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700811 int fd;
812 int ret;
813
814 if (persist_data == NULL) {
815 SLOGE("No persistent data to save");
816 return -1;
817 }
818
819 if(get_crypt_ftr_and_key(&crypt_ftr)) {
820 return -1;
821 }
822
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700823 if ((crypt_ftr.major_version < 1)
824 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700825 SLOGE("Crypt_ftr version doesn't support persistent data");
826 return -1;
827 }
828
829 ret = validate_persistent_data_storage(&crypt_ftr);
830 if (ret) {
831 return -1;
832 }
833
834 if (get_crypt_ftr_info(&fname, NULL)) {
835 return -1;
836 }
837
838 fd = open(fname, O_RDWR);
839 if (fd < 0) {
840 SLOGE("Cannot open %s metadata file", fname);
841 return -1;
842 }
843
844 pdata = malloc(crypt_ftr.persist_data_size);
845 if (pdata == NULL) {
846 SLOGE("Cannot allocate persistant data");
847 goto err;
848 }
849
850 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
851 SLOGE("Cannot seek to read persistent data on %s", fname);
852 goto err2;
853 }
854
855 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
856 SLOGE("Error reading persistent data before save");
857 goto err2;
858 }
859
860 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
861 /* The first copy is the curent valid copy, so write to
862 * the second copy and erase this one */
863 write_offset = crypt_ftr.persist_data_offset[1];
864 erase_offset = crypt_ftr.persist_data_offset[0];
865 } else {
866 /* The second copy must be the valid copy, so write to
867 * the first copy, and erase the second */
868 write_offset = crypt_ftr.persist_data_offset[0];
869 erase_offset = crypt_ftr.persist_data_offset[1];
870 }
871
872 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100873 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700874 SLOGE("Cannot seek to write persistent data");
875 goto err2;
876 }
877 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
878 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100879 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700880 SLOGE("Cannot seek to erase previous persistent data");
881 goto err2;
882 }
883 fsync(fd);
884 memset(pdata, 0, crypt_ftr.persist_data_size);
885 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
886 (int) crypt_ftr.persist_data_size) {
887 SLOGE("Cannot write to erase previous persistent data");
888 goto err2;
889 }
890 fsync(fd);
891 } else {
892 SLOGE("Cannot write to save persistent data");
893 goto err2;
894 }
895
896 /* Success */
897 free(pdata);
898 close(fd);
899 return 0;
900
901err2:
902 free(pdata);
903err:
904 close(fd);
905 return -1;
906}
907
Paul Lawrencef4faa572014-01-29 13:31:03 -0800908static int hexdigit (char c)
909{
910 if (c >= '0' && c <= '9') return c - '0';
911 c = tolower(c);
912 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
913 return -1;
914}
915
916static unsigned char* convert_hex_ascii_to_key(const char* master_key_ascii,
917 unsigned int* out_keysize)
918{
919 unsigned int i;
920 *out_keysize = 0;
921
922 size_t size = strlen (master_key_ascii);
923 if (size % 2) {
924 SLOGE("Trying to convert ascii string of odd length");
925 return NULL;
926 }
927
928 unsigned char* master_key = (unsigned char*) malloc(size / 2);
929 if (master_key == 0) {
930 SLOGE("Cannot allocate");
931 return NULL;
932 }
933
934 for (i = 0; i < size; i += 2) {
935 int high_nibble = hexdigit (master_key_ascii[i]);
936 int low_nibble = hexdigit (master_key_ascii[i + 1]);
937
938 if(high_nibble < 0 || low_nibble < 0) {
939 SLOGE("Invalid hex string");
940 free (master_key);
941 return NULL;
942 }
943
944 master_key[*out_keysize] = high_nibble * 16 + low_nibble;
945 (*out_keysize)++;
946 }
947
948 return master_key;
949}
950
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800951/* Convert a binary key of specified length into an ascii hex string equivalent,
952 * without the leading 0x and with null termination
953 */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800954static void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800955 char *master_key_ascii)
956{
957 unsigned int i, a;
958 unsigned char nibble;
959
960 for (i=0, a=0; i<keysize; i++, a+=2) {
961 /* For each byte, write out two ascii hex digits */
962 nibble = (master_key[i] >> 4) & 0xf;
963 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
964
965 nibble = master_key[i] & 0xf;
966 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
967 }
968
969 /* Add the null termination */
970 master_key_ascii[a] = '\0';
971
972}
973
Ken Sumralldb5e0262013-02-05 17:39:48 -0800974static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
975 char *real_blk_name, const char *name, int fd,
976 char *extra_params)
977{
Dan Albertc07fa3f2014-12-18 10:00:55 -0800978 _Alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800979 struct dm_ioctl *io;
980 struct dm_target_spec *tgt;
981 char *crypt_params;
982 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
983 int i;
984
985 io = (struct dm_ioctl *) buffer;
986
987 /* Load the mapping table for this device */
988 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
989
990 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
991 io->target_count = 1;
992 tgt->status = 0;
993 tgt->sector_start = 0;
994 tgt->length = crypt_ftr->fs_size;
995 strcpy(tgt->target_type, "crypt");
996
997 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
998 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
999 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
1000 master_key_ascii, real_blk_name, extra_params);
1001 crypt_params += strlen(crypt_params) + 1;
1002 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1003 tgt->next = crypt_params - buffer;
1004
1005 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1006 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
1007 break;
1008 }
1009 usleep(500000);
1010 }
1011
1012 if (i == TABLE_LOAD_RETRIES) {
1013 /* We failed to load the table, return an error */
1014 return -1;
1015 } else {
1016 return i + 1;
1017 }
1018}
1019
1020
1021static int get_dm_crypt_version(int fd, const char *name, int *version)
1022{
1023 char buffer[DM_CRYPT_BUF_SIZE];
1024 struct dm_ioctl *io;
1025 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001026
1027 io = (struct dm_ioctl *) buffer;
1028
1029 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1030
1031 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1032 return -1;
1033 }
1034
1035 /* Iterate over the returned versions, looking for name of "crypt".
1036 * When found, get and return the version.
1037 */
1038 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1039 while (v->next) {
1040 if (! strcmp(v->name, "crypt")) {
1041 /* We found the crypt driver, return the version, and get out */
1042 version[0] = v->version[0];
1043 version[1] = v->version[1];
1044 version[2] = v->version[2];
1045 return 0;
1046 }
1047 v = (struct dm_target_versions *)(((char *)v) + v->next);
1048 }
1049
1050 return -1;
1051}
1052
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001053static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -07001054 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001055{
1056 char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001057 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001058 unsigned int minor;
1059 int fd;
1060 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001061 int version[3];
1062 char *extra_params;
1063 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001064
1065 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1066 SLOGE("Cannot open device-mapper\n");
1067 goto errout;
1068 }
1069
1070 io = (struct dm_ioctl *) buffer;
1071
1072 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1073 if (ioctl(fd, DM_DEV_CREATE, io)) {
1074 SLOGE("Cannot create dm-crypt device\n");
1075 goto errout;
1076 }
1077
1078 /* Get the device status, in particular, the name of it's device file */
1079 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1080 if (ioctl(fd, DM_DEV_STATUS, io)) {
1081 SLOGE("Cannot retrieve dm-crypt device status\n");
1082 goto errout;
1083 }
1084 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1085 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1086
Ken Sumralldb5e0262013-02-05 17:39:48 -08001087 extra_params = "";
1088 if (! get_dm_crypt_version(fd, name, version)) {
1089 /* Support for allow_discards was added in version 1.11.0 */
1090 if ((version[0] >= 2) ||
1091 ((version[0] == 1) && (version[1] >= 11))) {
1092 extra_params = "1 allow_discards";
1093 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1094 }
Ken Sumralle919efe2012-09-29 17:07:41 -07001095 }
1096
Ken Sumralldb5e0262013-02-05 17:39:48 -08001097 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1098 fd, extra_params);
1099 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001100 SLOGE("Cannot load dm-crypt mapping table.\n");
1101 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001102 } else if (load_count > 1) {
1103 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001104 }
1105
1106 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -08001107 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001108
1109 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1110 SLOGE("Cannot resume the dm-crypt device\n");
1111 goto errout;
1112 }
1113
1114 /* We made it here with no errors. Woot! */
1115 retval = 0;
1116
1117errout:
1118 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1119
1120 return retval;
1121}
1122
Ken Sumrall29d8da82011-05-18 17:20:07 -07001123static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001124{
1125 int fd;
1126 char buffer[DM_CRYPT_BUF_SIZE];
1127 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001128 int retval = -1;
1129
1130 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1131 SLOGE("Cannot open device-mapper\n");
1132 goto errout;
1133 }
1134
1135 io = (struct dm_ioctl *) buffer;
1136
1137 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1138 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1139 SLOGE("Cannot remove dm-crypt device\n");
1140 goto errout;
1141 }
1142
1143 /* We made it here with no errors. Woot! */
1144 retval = 0;
1145
1146errout:
1147 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1148
1149 return retval;
1150
1151}
1152
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001153static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001154 unsigned char *ikey, void *params UNUSED)
1155{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001156 SLOGI("Using pbkdf2 for cryptfs KDF");
1157
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001158 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001159 unsigned int keysize;
1160 char* master_key = (char*)convert_hex_ascii_to_key(passwd, &keysize);
1161 if (!master_key) return -1;
1162 PKCS5_PBKDF2_HMAC_SHA1(master_key, keysize, salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001163 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001164
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001165 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001166 free (master_key);
1167 return 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001168}
1169
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001170static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001171 unsigned char *ikey, void *params)
1172{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001173 SLOGI("Using scrypt for cryptfs KDF");
1174
Kenny Rootc4c70f12013-06-14 12:11:38 -07001175 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1176
1177 int N = 1 << ftr->N_factor;
1178 int r = 1 << ftr->r_factor;
1179 int p = 1 << ftr->p_factor;
1180
1181 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001182 unsigned int keysize;
1183 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &keysize);
1184 if (!master_key) return -1;
1185 crypto_scrypt(master_key, keysize, salt, SALT_LEN, N, r, p, ikey,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001186 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001187
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001188 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001189 free (master_key);
1190 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001191}
1192
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001193static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1194 unsigned char *ikey, void *params)
1195{
1196 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1197
1198 int rc;
1199 unsigned int key_size;
1200 size_t signature_size;
1201 unsigned char* signature;
1202 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1203
1204 int N = 1 << ftr->N_factor;
1205 int r = 1 << ftr->r_factor;
1206 int p = 1 << ftr->p_factor;
1207
1208 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &key_size);
1209 if (!master_key) {
1210 SLOGE("Failed to convert passwd from hex");
1211 return -1;
1212 }
1213
1214 rc = crypto_scrypt(master_key, key_size, salt, SALT_LEN,
1215 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1216 memset(master_key, 0, key_size);
1217 free(master_key);
1218
1219 if (rc) {
1220 SLOGE("scrypt failed");
1221 return -1;
1222 }
1223
Shawn Willdene17a9c42014-09-08 13:04:08 -06001224 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1225 &signature, &signature_size)) {
1226 SLOGE("Signing failed");
1227 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001228 }
1229
1230 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1231 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1232 free(signature);
1233
1234 if (rc) {
1235 SLOGE("scrypt failed");
1236 return -1;
1237 }
1238
1239 return 0;
1240}
1241
1242static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1243 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001244 unsigned char *encrypted_master_key,
1245 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001246{
1247 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1248 EVP_CIPHER_CTX e_ctx;
1249 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001250 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001251
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001252 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001253 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001254
1255 switch (crypt_ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001256 case KDF_SCRYPT_KEYMASTER_UNPADDED:
1257 case KDF_SCRYPT_KEYMASTER_BADLY_PADDED:
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001258 case KDF_SCRYPT_KEYMASTER:
1259 if (keymaster_create_key(crypt_ftr)) {
1260 SLOGE("keymaster_create_key failed");
1261 return -1;
1262 }
1263
1264 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1265 SLOGE("scrypt failed");
1266 return -1;
1267 }
1268 break;
1269
1270 case KDF_SCRYPT:
1271 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1272 SLOGE("scrypt failed");
1273 return -1;
1274 }
1275 break;
1276
1277 default:
1278 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001279 return -1;
1280 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001281
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001282 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001283 EVP_CIPHER_CTX_init(&e_ctx);
1284 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001285 SLOGE("EVP_EncryptInit failed\n");
1286 return -1;
1287 }
1288 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001289
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001290 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001291 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
1292 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001293 SLOGE("EVP_EncryptUpdate failed\n");
1294 return -1;
1295 }
Adam Langley889c4f12014-09-03 14:23:13 -07001296 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001297 SLOGE("EVP_EncryptFinal failed\n");
1298 return -1;
1299 }
1300
1301 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1302 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1303 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001304 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001305
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001306 /* Store the scrypt of the intermediate key, so we can validate if it's a
1307 password error or mount error when things go wrong.
1308 Note there's no need to check for errors, since if this is incorrect, we
1309 simply won't wipe userdata, which is the correct default behavior
1310 */
1311 int N = 1 << crypt_ftr->N_factor;
1312 int r = 1 << crypt_ftr->r_factor;
1313 int p = 1 << crypt_ftr->p_factor;
1314
1315 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1316 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1317 crypt_ftr->scrypted_intermediate_key,
1318 sizeof(crypt_ftr->scrypted_intermediate_key));
1319
1320 if (rc) {
1321 SLOGE("encrypt_master_key: crypto_scrypt failed");
1322 }
1323
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001324 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001325}
1326
JP Abgrall7bdfa522013-11-15 13:42:56 -08001327static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001328 unsigned char *encrypted_master_key,
1329 unsigned char *decrypted_master_key,
1330 kdf_func kdf, void *kdf_params,
1331 unsigned char** intermediate_key,
1332 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001333{
1334 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 -08001335 EVP_CIPHER_CTX d_ctx;
1336 int decrypted_len, final_len;
1337
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001338 /* Turn the password into an intermediate key and IV that can decrypt the
1339 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001340 if (kdf(passwd, salt, ikey, kdf_params)) {
1341 SLOGE("kdf failed");
1342 return -1;
1343 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001344
1345 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001346 EVP_CIPHER_CTX_init(&d_ctx);
1347 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001348 return -1;
1349 }
1350 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1351 /* Decrypt the master key */
1352 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1353 encrypted_master_key, KEY_LEN_BYTES)) {
1354 return -1;
1355 }
Adam Langley889c4f12014-09-03 14:23:13 -07001356 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001357 return -1;
1358 }
1359
1360 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1361 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001362 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001363
1364 /* Copy intermediate key if needed by params */
1365 if (intermediate_key && intermediate_key_size) {
1366 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1367 if (intermediate_key) {
1368 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1369 *intermediate_key_size = KEY_LEN_BYTES;
1370 }
1371 }
1372
1373 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001374}
1375
Kenny Rootc4c70f12013-06-14 12:11:38 -07001376static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001377{
Shawn Willdene17a9c42014-09-08 13:04:08 -06001378 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER_UNPADDED ||
1379 ftr->kdf_type == KDF_SCRYPT_KEYMASTER_BADLY_PADDED ||
1380 ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001381 *kdf = scrypt_keymaster;
1382 *kdf_params = ftr;
1383 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001384 *kdf = scrypt;
1385 *kdf_params = ftr;
1386 } else {
1387 *kdf = pbkdf2;
1388 *kdf_params = NULL;
1389 }
1390}
1391
JP Abgrall7bdfa522013-11-15 13:42:56 -08001392static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001393 struct crypt_mnt_ftr *crypt_ftr,
1394 unsigned char** intermediate_key,
1395 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001396{
1397 kdf_func kdf;
1398 void *kdf_params;
1399 int ret;
1400
1401 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001402 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1403 decrypted_master_key, kdf, kdf_params,
1404 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001405 if (ret != 0) {
1406 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001407 }
1408
1409 return ret;
1410}
1411
1412static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1413 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001414 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001415 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001416
1417 /* Get some random bits for a key */
1418 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001419 read(fd, key_buf, sizeof(key_buf));
1420 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001421 close(fd);
1422
1423 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001424 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001425}
1426
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001427static int wait_and_unmount(char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001428{
Greg Hackmann955653e2014-09-24 14:55:20 -07001429 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001430#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001431
1432 /* Now umount the tmpfs filesystem */
1433 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001434 if (umount(mountpoint) == 0) {
1435 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001436 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001437
1438 if (errno == EINVAL) {
1439 /* EINVAL is returned if the directory is not a mountpoint,
1440 * i.e. there is no filesystem mounted there. So just get out.
1441 */
1442 break;
1443 }
1444
1445 err = errno;
1446
1447 /* If allowed, be increasingly aggressive before the last two retries */
1448 if (kill) {
1449 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1450 SLOGW("sending SIGHUP to processes with open files\n");
1451 vold_killProcessesWithOpenFiles(mountpoint, 1);
1452 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1453 SLOGW("sending SIGKILL to processes with open files\n");
1454 vold_killProcessesWithOpenFiles(mountpoint, 2);
1455 }
1456 }
1457
1458 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001459 }
1460
1461 if (i < WAIT_UNMOUNT_COUNT) {
1462 SLOGD("unmounting %s succeeded\n", mountpoint);
1463 rc = 0;
1464 } else {
jessica_yu3f14fe42014-09-22 15:57:40 +08001465 vold_killProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001466 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001467 rc = -1;
1468 }
1469
1470 return rc;
1471}
1472
Ken Sumrallc5872692013-05-14 15:26:31 -07001473#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001474static int prep_data_fs(void)
1475{
1476 int i;
1477
1478 /* Do the prep of the /data filesystem */
1479 property_set("vold.post_fs_data_done", "0");
1480 property_set("vold.decrypt", "trigger_post_fs_data");
1481 SLOGD("Just triggered post_fs_data\n");
1482
Ken Sumrallc5872692013-05-14 15:26:31 -07001483 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001484 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001485 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001486
1487 property_get("vold.post_fs_data_done", p, "0");
1488 if (*p == '1') {
1489 break;
1490 } else {
1491 usleep(250000);
1492 }
1493 }
1494 if (i == DATA_PREP_TIMEOUT) {
1495 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001496 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001497 return -1;
1498 } else {
1499 SLOGD("post_fs_data done\n");
1500 return 0;
1501 }
1502}
1503
Paul Lawrence74f29f12014-08-28 15:54:10 -07001504static void cryptfs_set_corrupt()
1505{
1506 // Mark the footer as bad
1507 struct crypt_mnt_ftr crypt_ftr;
1508 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1509 SLOGE("Failed to get crypto footer - panic");
1510 return;
1511 }
1512
1513 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1514 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1515 SLOGE("Failed to set crypto footer - panic");
1516 return;
1517 }
1518}
1519
1520static void cryptfs_trigger_restart_min_framework()
1521{
1522 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1523 SLOGE("Failed to mount tmpfs on data - panic");
1524 return;
1525 }
1526
1527 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1528 SLOGE("Failed to trigger post fs data - panic");
1529 return;
1530 }
1531
1532 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1533 SLOGE("Failed to trigger restart min framework - panic");
1534 return;
1535 }
1536}
1537
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001538/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001539static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001540{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001541 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001542 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001543 static int restart_successful = 0;
1544
1545 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001546 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001547 SLOGE("Encrypted filesystem not validated, aborting");
1548 return -1;
1549 }
1550
1551 if (restart_successful) {
1552 SLOGE("System already restarted with encrypted disk, aborting");
1553 return -1;
1554 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001555
Paul Lawrencef4faa572014-01-29 13:31:03 -08001556 if (restart_main) {
1557 /* Here is where we shut down the framework. The init scripts
1558 * start all services in one of three classes: core, main or late_start.
1559 * On boot, we start core and main. Now, we stop main, but not core,
1560 * as core includes vold and a few other really important things that
1561 * we need to keep running. Once main has stopped, we should be able
1562 * to umount the tmpfs /data, then mount the encrypted /data.
1563 * We then restart the class main, and also the class late_start.
1564 * At the moment, I've only put a few things in late_start that I know
1565 * are not needed to bring up the framework, and that also cause problems
1566 * with unmounting the tmpfs /data, but I hope to add add more services
1567 * to the late_start class as we optimize this to decrease the delay
1568 * till the user is asked for the password to the filesystem.
1569 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001570
Paul Lawrencef4faa572014-01-29 13:31:03 -08001571 /* The init files are setup to stop the class main when vold.decrypt is
1572 * set to trigger_reset_main.
1573 */
1574 property_set("vold.decrypt", "trigger_reset_main");
1575 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001576
Paul Lawrencef4faa572014-01-29 13:31:03 -08001577 /* Ugh, shutting down the framework is not synchronous, so until it
1578 * can be fixed, this horrible hack will wait a moment for it all to
1579 * shut down before proceeding. Without it, some devices cannot
1580 * restart the graphics services.
1581 */
1582 sleep(2);
1583 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001584
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001585 /* Now that the framework is shutdown, we should be able to umount()
1586 * the tmpfs filesystem, and mount the real one.
1587 */
1588
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001589 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1590 if (strlen(crypto_blkdev) == 0) {
1591 SLOGE("fs_crypto_blkdev not set\n");
1592 return -1;
1593 }
1594
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001595 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001596 /* If ro.crypto.readonly is set to 1, mount the decrypted
1597 * filesystem readonly. This is used when /data is mounted by
1598 * recovery mode.
1599 */
1600 char ro_prop[PROPERTY_VALUE_MAX];
1601 property_get("ro.crypto.readonly", ro_prop, "");
1602 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1603 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1604 rec->flags |= MS_RDONLY;
1605 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001606
Ken Sumralle5032c42012-04-01 23:58:44 -07001607 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001608 int retries = RETRY_MOUNT_ATTEMPTS;
1609 int mount_rc;
1610 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1611 crypto_blkdev, 0))
1612 != 0) {
1613 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1614 /* TODO: invoke something similar to
1615 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1616 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1617 SLOGI("Failed to mount %s because it is busy - waiting",
1618 crypto_blkdev);
1619 if (--retries) {
1620 sleep(RETRY_MOUNT_DELAY_SECONDS);
1621 } else {
1622 /* Let's hope that a reboot clears away whatever is keeping
1623 the mount busy */
1624 cryptfs_reboot(reboot);
1625 }
1626 } else {
1627 SLOGE("Failed to mount decrypted data");
1628 cryptfs_set_corrupt();
1629 cryptfs_trigger_restart_min_framework();
1630 SLOGI("Started framework to offer wipe");
1631 return -1;
1632 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001633 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001634
Ken Sumralle5032c42012-04-01 23:58:44 -07001635 property_set("vold.decrypt", "trigger_load_persist_props");
1636 /* Create necessary paths on /data */
1637 if (prep_data_fs()) {
1638 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001639 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001640
1641 /* startup service classes main and late_start */
1642 property_set("vold.decrypt", "trigger_restart_framework");
1643 SLOGD("Just triggered restart_framework\n");
1644
1645 /* Give it a few moments to get started */
1646 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001647 }
1648
Ken Sumrall0cc16632011-01-18 20:32:26 -08001649 if (rc == 0) {
1650 restart_successful = 1;
1651 }
1652
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001653 return rc;
1654}
1655
Paul Lawrencef4faa572014-01-29 13:31:03 -08001656int cryptfs_restart(void)
1657{
1658 /* Call internal implementation forcing a restart of main service group */
1659 return cryptfs_restart_internal(1);
1660}
1661
Mark Salyzyn3e971272014-01-21 13:27:04 -08001662static int do_crypto_complete(char *mount_point UNUSED)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001663{
1664 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001665 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001666 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001667
1668 property_get("ro.crypto.state", encrypted_state, "");
1669 if (strcmp(encrypted_state, "encrypted") ) {
1670 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001671 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001672 }
1673
Ken Sumrall160b4d62013-04-22 12:15:39 -07001674 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001675 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001676
Ken Sumralle1a45852011-12-14 21:24:27 -08001677 /*
1678 * Only report this error if key_loc is a file and it exists.
1679 * If the device was never encrypted, and /data is not mountable for
1680 * some reason, returning 1 should prevent the UI from presenting the
1681 * a "enter password" screen, or worse, a "press button to wipe the
1682 * device" screen.
1683 */
1684 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1685 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001686 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001687 } else {
1688 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001689 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001690 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001691 }
1692
Paul Lawrence74f29f12014-08-28 15:54:10 -07001693 // Test for possible error flags
1694 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1695 SLOGE("Encryption process is partway completed\n");
1696 return CRYPTO_COMPLETE_PARTIAL;
1697 }
1698
1699 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1700 SLOGE("Encryption process was interrupted but cannot continue\n");
1701 return CRYPTO_COMPLETE_INCONSISTENT;
1702 }
1703
1704 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1705 SLOGE("Encryption is successful but data is corrupt\n");
1706 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001707 }
1708
1709 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001710 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001711}
1712
Paul Lawrencef4faa572014-01-29 13:31:03 -08001713static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1714 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001715{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001716 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001717 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001718 char crypto_blkdev[MAXPATHLEN];
1719 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001720 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001721 unsigned int orig_failed_decrypt_count;
1722 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001723 int use_keymaster = 0;
1724 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001725 unsigned char* intermediate_key = 0;
1726 size_t intermediate_key_size = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001727
Paul Lawrencef4faa572014-01-29 13:31:03 -08001728 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1729 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001730
Paul Lawrencef4faa572014-01-29 13:31:03 -08001731 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001732 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1733 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001734 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001735 rc = -1;
1736 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001737 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001738 }
1739
Paul Lawrencef4faa572014-01-29 13:31:03 -08001740 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1741
Paul Lawrence74f29f12014-08-28 15:54:10 -07001742 // Create crypto block device - all (non fatal) code paths
1743 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001744 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1745 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001746 SLOGE("Error creating decrypted block device\n");
1747 rc = -1;
1748 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001749 }
1750
Paul Lawrence74f29f12014-08-28 15:54:10 -07001751 /* Work out if the problem is the password or the data */
1752 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1753 scrypted_intermediate_key)];
1754 int N = 1 << crypt_ftr->N_factor;
1755 int r = 1 << crypt_ftr->r_factor;
1756 int p = 1 << crypt_ftr->p_factor;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001757
Paul Lawrence74f29f12014-08-28 15:54:10 -07001758 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1759 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1760 N, r, p, scrypted_intermediate_key,
1761 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001762
Paul Lawrence74f29f12014-08-28 15:54:10 -07001763 // Does the key match the crypto footer?
1764 if (rc == 0 && memcmp(scrypted_intermediate_key,
1765 crypt_ftr->scrypted_intermediate_key,
1766 sizeof(scrypted_intermediate_key)) == 0) {
1767 SLOGI("Password matches");
1768 rc = 0;
1769 } else {
1770 /* Try mounting the file system anyway, just in case the problem's with
1771 * the footer, not the key. */
1772 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1773 mkdir(tmp_mount_point, 0755);
1774 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1775 SLOGE("Error temp mounting decrypted block device\n");
1776 delete_crypto_blk_dev(label);
1777
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001778 rc = ++crypt_ftr->failed_decrypt_count;
1779 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001780 } else {
1781 /* Success! */
1782 SLOGI("Password did not match but decrypted drive mounted - continue");
1783 umount(tmp_mount_point);
1784 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001785 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001786 }
1787
1788 if (rc == 0) {
1789 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001790 if (orig_failed_decrypt_count != 0) {
1791 put_crypt_ftr_and_key(crypt_ftr);
1792 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001793
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001794 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001795 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001796 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001797
1798 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001799 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001800 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001801 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001802 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001803 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001804 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001805
Paul Lawrence74f29f12014-08-28 15:54:10 -07001806 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001807 use_keymaster = keymaster_check_compatibility();
1808 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001809 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001810 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1811 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1812 upgrade = 1;
1813 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001814 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001815 upgrade = 1;
1816 }
1817
1818 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001819 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1820 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001821 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001822 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001823 }
1824 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001825
1826 // Do not fail even if upgrade failed - machine is bootable
1827 // Note that if this code is ever hit, there is a *serious* problem
1828 // since KDFs should never fail. You *must* fix the kdf before
1829 // proceeding!
1830 if (rc) {
1831 SLOGW("Upgrade failed with error %d,"
1832 " but continuing with previous state",
1833 rc);
1834 rc = 0;
1835 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001836 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001837 }
1838
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001839 errout:
1840 if (intermediate_key) {
1841 memset(intermediate_key, 0, intermediate_key_size);
1842 free(intermediate_key);
1843 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001844 return rc;
1845}
1846
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001847/* Called by vold when it wants to undo the crypto mapping of a volume it
1848 * manages. This is usually in response to a factory reset, when we want
1849 * to undo the crypto mapping so the volume is formatted in the clear.
1850 */
1851int cryptfs_revert_volume(const char *label)
1852{
1853 return delete_crypto_blk_dev((char *)label);
1854}
1855
Ken Sumrall29d8da82011-05-18 17:20:07 -07001856/*
1857 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1858 * Setup a dm-crypt mapping, use the saved master key from
1859 * setting up the /data mapping, and return the new device path.
1860 */
1861int cryptfs_setup_volume(const char *label, int major, int minor,
1862 char *crypto_sys_path, unsigned int max_path,
1863 int *new_major, int *new_minor)
1864{
1865 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1866 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001867 struct stat statbuf;
Tim Murray8439dc92014-12-15 11:56:11 -08001868 unsigned int nr_sec;
1869 int fd;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001870
1871 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1872
Ken Sumrall160b4d62013-04-22 12:15:39 -07001873 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001874
1875 /* Update the fs_size field to be the size of the volume */
1876 fd = open(real_blkdev, O_RDONLY);
1877 nr_sec = get_blkdev_size(fd);
1878 close(fd);
1879 if (nr_sec == 0) {
1880 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1881 return -1;
1882 }
1883
1884 sd_crypt_ftr.fs_size = nr_sec;
1885 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1886 crypto_blkdev, label);
1887
1888 stat(crypto_blkdev, &statbuf);
1889 *new_major = MAJOR(statbuf.st_rdev);
1890 *new_minor = MINOR(statbuf.st_rdev);
1891
1892 /* Create path to sys entry for this block device */
1893 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1894
1895 return 0;
1896}
1897
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001898int cryptfs_crypto_complete(void)
1899{
1900 return do_crypto_complete("/data");
1901}
1902
Paul Lawrencef4faa572014-01-29 13:31:03 -08001903int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1904{
1905 char encrypted_state[PROPERTY_VALUE_MAX];
1906 property_get("ro.crypto.state", encrypted_state, "");
1907 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1908 SLOGE("encrypted fs already validated or not running with encryption,"
1909 " aborting");
1910 return -1;
1911 }
1912
1913 if (get_crypt_ftr_and_key(crypt_ftr)) {
1914 SLOGE("Error getting crypt footer and key");
1915 return -1;
1916 }
1917
1918 return 0;
1919}
1920
Paul Lawrencefc615042014-10-04 15:32:29 -07001921/*
1922 * TODO - transition patterns to new format in calling code
1923 * and remove this vile hack, and the use of hex in
1924 * the password passing code.
1925 *
1926 * Patterns are passed in zero based (i.e. the top left dot
1927 * is represented by zero, the top middle one etc), but we want
1928 * to store them '1' based.
1929 * This is to allow us to migrate the calling code to use this
1930 * convention. It also solves a nasty problem whereby scrypt ignores
1931 * trailing zeros, so patterns ending at the top left could be
1932 * truncated, and similarly, you could add the top left to any
1933 * pattern and still match.
1934 * adjust_passwd is a hack function that returns the alternate representation
1935 * if the password appears to be a pattern (hex numbers all less than 09)
1936 * If it succeeds we need to try both, and in particular try the alternate
1937 * first. If the original matches, then we need to update the footer
1938 * with the alternate.
1939 * All code that accepts passwords must adjust them first. Since
1940 * cryptfs_check_passwd is always the first function called after a migration
1941 * (and indeed on any boot) we only need to do the double try in this
1942 * function.
1943 */
1944char* adjust_passwd(const char* passwd)
1945{
1946 size_t index, length;
1947
1948 if (!passwd) {
1949 return 0;
1950 }
1951
1952 // Check even length. Hex encoded passwords are always
1953 // an even length, since each character encodes to two characters.
1954 length = strlen(passwd);
1955 if (length % 2) {
1956 SLOGW("Password not correctly hex encoded.");
1957 return 0;
1958 }
1959
1960 // Check password is old-style pattern - a collection of hex
1961 // encoded bytes less than 9 (00 through 08)
1962 for (index = 0; index < length; index +=2) {
1963 if (passwd[index] != '0'
1964 || passwd[index + 1] < '0' || passwd[index + 1] > '8') {
1965 return 0;
1966 }
1967 }
1968
1969 // Allocate room for adjusted passwd and null terminate
1970 char* adjusted = malloc(length + 1);
1971 adjusted[length] = 0;
1972
1973 // Add 0x31 ('1') to each character
1974 for (index = 0; index < length; index += 2) {
1975 // output is 31 through 39 so set first byte to three, second to src + 1
1976 adjusted[index] = '3';
1977 adjusted[index + 1] = passwd[index + 1] + 1;
1978 }
1979
1980 return adjusted;
1981}
1982
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001983int cryptfs_check_passwd(char *passwd)
1984{
Paul Lawrencef4faa572014-01-29 13:31:03 -08001985 struct crypt_mnt_ftr crypt_ftr;
1986 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001987
Paul Lawrencef4faa572014-01-29 13:31:03 -08001988 rc = check_unmounted_and_get_ftr(&crypt_ftr);
1989 if (rc)
1990 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001991
Paul Lawrencefc615042014-10-04 15:32:29 -07001992 char* adjusted_passwd = adjust_passwd(passwd);
1993 if (adjusted_passwd) {
1994 int failed_decrypt_count = crypt_ftr.failed_decrypt_count;
1995 rc = test_mount_encrypted_fs(&crypt_ftr, adjusted_passwd,
1996 DATA_MNT_POINT, "userdata");
1997
1998 // Maybe the original one still works?
1999 if (rc) {
2000 // Don't double count this failure
2001 crypt_ftr.failed_decrypt_count = failed_decrypt_count;
2002 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
2003 DATA_MNT_POINT, "userdata");
2004 if (!rc) {
2005 // cryptfs_changepw also adjusts so pass original
2006 // Note that adjust_passwd only recognises patterns
2007 // so we can safely use CRYPT_TYPE_PATTERN
2008 SLOGI("Updating pattern to new format");
2009 cryptfs_changepw(CRYPT_TYPE_PATTERN, passwd);
2010 }
2011 }
2012 free(adjusted_passwd);
2013 } else {
2014 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
2015 DATA_MNT_POINT, "userdata");
2016 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002017
2018 if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002019 cryptfs_clear_password();
2020 password = strdup(passwd);
2021 struct timespec now;
2022 clock_gettime(CLOCK_BOOTTIME, &now);
2023 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002024 }
2025
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002026 return rc;
2027}
2028
Ken Sumrall3ad90722011-10-04 20:38:29 -07002029int cryptfs_verify_passwd(char *passwd)
2030{
2031 struct crypt_mnt_ftr crypt_ftr;
2032 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002033 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002034 char encrypted_state[PROPERTY_VALUE_MAX];
2035 int rc;
2036
2037 property_get("ro.crypto.state", encrypted_state, "");
2038 if (strcmp(encrypted_state, "encrypted") ) {
2039 SLOGE("device not encrypted, aborting");
2040 return -2;
2041 }
2042
2043 if (!master_key_saved) {
2044 SLOGE("encrypted fs not yet mounted, aborting");
2045 return -1;
2046 }
2047
2048 if (!saved_mount_point) {
2049 SLOGE("encrypted fs failed to save mount point, aborting");
2050 return -1;
2051 }
2052
Ken Sumrall160b4d62013-04-22 12:15:39 -07002053 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002054 SLOGE("Error getting crypt footer and key\n");
2055 return -1;
2056 }
2057
2058 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2059 /* If the device has no password, then just say the password is valid */
2060 rc = 0;
2061 } else {
Paul Lawrencefc615042014-10-04 15:32:29 -07002062 char* adjusted_passwd = adjust_passwd(passwd);
2063 if (adjusted_passwd) {
2064 passwd = adjusted_passwd;
2065 }
2066
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002067 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002068 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2069 /* They match, the password is correct */
2070 rc = 0;
2071 } else {
2072 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2073 sleep(1);
2074 rc = 1;
2075 }
Paul Lawrencefc615042014-10-04 15:32:29 -07002076
2077 free(adjusted_passwd);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002078 }
2079
2080 return rc;
2081}
2082
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002083/* Initialize a crypt_mnt_ftr structure. The keysize is
2084 * defaulted to 16 bytes, and the filesystem size to 0.
2085 * Presumably, at a minimum, the caller will update the
2086 * filesystem size and crypto_type_name after calling this function.
2087 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002088static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002089{
Ken Sumrall160b4d62013-04-22 12:15:39 -07002090 off64_t off;
2091
2092 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002093 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002094 ftr->major_version = CURRENT_MAJOR_VERSION;
2095 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002096 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06002097 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002098
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002099 switch (keymaster_check_compatibility()) {
2100 case 1:
2101 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2102 break;
2103
2104 case 0:
2105 ftr->kdf_type = KDF_SCRYPT;
2106 break;
2107
2108 default:
2109 SLOGE("keymaster_check_compatibility failed");
2110 return -1;
2111 }
2112
Kenny Rootc4c70f12013-06-14 12:11:38 -07002113 get_device_scrypt_params(ftr);
2114
Ken Sumrall160b4d62013-04-22 12:15:39 -07002115 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2116 if (get_crypt_ftr_info(NULL, &off) == 0) {
2117 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
2118 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
2119 ftr->persist_data_size;
2120 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002121
2122 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002123}
2124
Ken Sumrall29d8da82011-05-18 17:20:07 -07002125static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002126{
Ken Sumralle550f782013-08-20 13:48:23 -07002127 const char *args[10];
2128 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
2129 int num_args;
2130 int status;
2131 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002132 int rc = -1;
2133
Ken Sumrall29d8da82011-05-18 17:20:07 -07002134 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07002135 args[0] = "/system/bin/make_ext4fs";
2136 args[1] = "-a";
2137 args[2] = "/data";
2138 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07002139 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07002140 args[4] = size_str;
2141 args[5] = crypto_blkdev;
2142 num_args = 6;
2143 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
2144 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07002145 } else if (type == F2FS_FS) {
2146 args[0] = "/system/bin/mkfs.f2fs";
2147 args[1] = "-t";
2148 args[2] = "-d1";
2149 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07002150 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07002151 args[4] = size_str;
2152 num_args = 5;
2153 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
2154 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002155 } else {
2156 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
2157 return -1;
2158 }
2159
Ken Sumralle550f782013-08-20 13:48:23 -07002160 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
2161
2162 if (tmp != 0) {
2163 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002164 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07002165 if (WIFEXITED(status)) {
2166 if (WEXITSTATUS(status)) {
2167 SLOGE("Error creating filesystem on %s, exit status %d ",
2168 crypto_blkdev, WEXITSTATUS(status));
2169 } else {
2170 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
2171 rc = 0;
2172 }
2173 } else {
2174 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
2175 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002176 }
2177
2178 return rc;
2179}
2180
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002181#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08002182#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
2183#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002184
2185/* aligned 32K writes tends to make flash happy.
2186 * SD card association recommends it.
2187 */
2188#define BLOCKS_AT_A_TIME 8
2189
2190struct encryptGroupsData
2191{
2192 int realfd;
2193 int cryptofd;
2194 off64_t numblocks;
2195 off64_t one_pct, cur_pct, new_pct;
2196 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002197 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002198 char* real_blkdev, * crypto_blkdev;
2199 int count;
2200 off64_t offset;
2201 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08002202 off64_t last_written_sector;
2203 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002204 time_t time_started;
2205 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002206};
2207
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002208static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002209{
2210 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002211
2212 if (is_used) {
2213 data->used_blocks_already_done++;
2214 }
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002215 if (data->tot_used_blocks) {
2216 data->new_pct = data->used_blocks_already_done / data->one_pct;
2217 } else {
2218 data->new_pct = data->blocks_already_done / data->one_pct;
2219 }
2220
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002221 if (data->new_pct > data->cur_pct) {
2222 char buf[8];
2223 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07002224 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002225 property_set("vold.encrypt_progress", buf);
2226 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002227
2228 if (data->cur_pct >= 5) {
Paul Lawrence9c58a872014-09-30 09:12:51 -07002229 struct timespec time_now;
2230 if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
2231 SLOGW("Error getting time");
2232 } else {
2233 double elapsed_time = difftime(time_now.tv_sec, data->time_started);
2234 off64_t remaining_blocks = data->tot_used_blocks
2235 - data->used_blocks_already_done;
2236 int remaining_time = (int)(elapsed_time * remaining_blocks
2237 / data->used_blocks_already_done);
Paul Lawrence71577502014-08-13 14:55:55 -07002238
Paul Lawrence9c58a872014-09-30 09:12:51 -07002239 // Change time only if not yet set, lower, or a lot higher for
2240 // best user experience
2241 if (data->remaining_time == -1
2242 || remaining_time < data->remaining_time
2243 || remaining_time > data->remaining_time + 60) {
2244 char buf[8];
2245 snprintf(buf, sizeof(buf), "%d", remaining_time);
2246 property_set("vold.encrypt_time_remaining", buf);
2247 data->remaining_time = remaining_time;
2248 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002249 }
2250 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002251}
2252
Paul Lawrence3846be12014-09-22 11:33:54 -07002253static void log_progress(struct encryptGroupsData const* data, bool completed)
2254{
2255 // Precondition - if completed data = 0 else data != 0
2256
2257 // Track progress so we can skip logging blocks
2258 static off64_t offset = -1;
2259
2260 // Need to close existing 'Encrypting from' log?
2261 if (completed || (offset != -1 && data->offset != offset)) {
2262 SLOGI("Encrypted to sector %" PRId64,
2263 offset / info.block_size * CRYPT_SECTOR_SIZE);
2264 offset = -1;
2265 }
2266
2267 // Need to start new 'Encrypting from' log?
2268 if (!completed && offset != data->offset) {
2269 SLOGI("Encrypting from sector %" PRId64,
2270 data->offset / info.block_size * CRYPT_SECTOR_SIZE);
2271 }
2272
2273 // Update offset
2274 if (!completed) {
2275 offset = data->offset + (off64_t)data->count * info.block_size;
2276 }
2277}
2278
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002279static int flush_outstanding_data(struct encryptGroupsData* data)
2280{
2281 if (data->count == 0) {
2282 return 0;
2283 }
2284
Elliott Hughes231bdba2014-06-25 18:36:19 -07002285 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002286
2287 if (pread64(data->realfd, data->buffer,
2288 info.block_size * data->count, data->offset)
2289 <= 0) {
2290 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2291 data->real_blkdev);
2292 return -1;
2293 }
2294
2295 if (pwrite64(data->cryptofd, data->buffer,
2296 info.block_size * data->count, data->offset)
2297 <= 0) {
2298 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2299 data->crypto_blkdev);
2300 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002301 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002302 log_progress(data, false);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002303 }
2304
2305 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002306 data->last_written_sector = (data->offset + data->count)
2307 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002308 return 0;
2309}
2310
2311static int encrypt_groups(struct encryptGroupsData* data)
2312{
2313 unsigned int i;
2314 u8 *block_bitmap = 0;
2315 unsigned int block;
2316 off64_t ret;
2317 int rc = -1;
2318
2319 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
2320 if (!data->buffer) {
2321 SLOGE("Failed to allocate crypto buffer");
2322 goto errout;
2323 }
2324
2325 block_bitmap = malloc(info.block_size);
2326 if (!block_bitmap) {
2327 SLOGE("failed to allocate block bitmap");
2328 goto errout;
2329 }
2330
2331 for (i = 0; i < aux_info.groups; ++i) {
2332 SLOGI("Encrypting group %d", i);
2333
2334 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2335 u32 block_count = min(info.blocks_per_group,
2336 aux_info.len_blocks - first_block);
2337
2338 off64_t offset = (u64)info.block_size
2339 * aux_info.bg_desc[i].bg_block_bitmap;
2340
2341 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2342 if (ret != (int)info.block_size) {
2343 SLOGE("failed to read all of block group bitmap %d", i);
2344 goto errout;
2345 }
2346
2347 offset = (u64)info.block_size * first_block;
2348
2349 data->count = 0;
2350
2351 for (block = 0; block < block_count; block++) {
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002352 int used = bitmap_get_bit(block_bitmap, block);
2353 update_progress(data, used);
2354 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002355 if (data->count == 0) {
2356 data->offset = offset;
2357 }
2358 data->count++;
2359 } else {
2360 if (flush_outstanding_data(data)) {
2361 goto errout;
2362 }
2363 }
2364
2365 offset += info.block_size;
2366
2367 /* Write data if we are aligned or buffer size reached */
2368 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2369 || data->count == BLOCKS_AT_A_TIME) {
2370 if (flush_outstanding_data(data)) {
2371 goto errout;
2372 }
2373 }
Paul Lawrence87999172014-02-20 12:21:31 -08002374
Paul Lawrence73d7a022014-06-09 14:10:09 -07002375 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002376 SLOGE("Stopping encryption due to low battery");
2377 rc = 0;
2378 goto errout;
2379 }
2380
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002381 }
2382 if (flush_outstanding_data(data)) {
2383 goto errout;
2384 }
2385 }
2386
Paul Lawrence87999172014-02-20 12:21:31 -08002387 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002388 rc = 0;
2389
2390errout:
Paul Lawrence3846be12014-09-22 11:33:54 -07002391 log_progress(0, true);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002392 free(data->buffer);
2393 free(block_bitmap);
2394 return rc;
2395}
2396
2397static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2398 char *real_blkdev,
2399 off64_t size,
2400 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002401 off64_t tot_size,
2402 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002403{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002404 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002405 struct encryptGroupsData data;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002406 int rc; // Can't initialize without causing warning -Wclobbered
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002407
Paul Lawrence87999172014-02-20 12:21:31 -08002408 if (previously_encrypted_upto > *size_already_done) {
2409 SLOGD("Not fast encrypting since resuming part way through");
2410 return -1;
2411 }
2412
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002413 memset(&data, 0, sizeof(data));
2414 data.real_blkdev = real_blkdev;
2415 data.crypto_blkdev = crypto_blkdev;
2416
2417 if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
JP Abgrall77768712014-10-10 15:52:11 -07002418 SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
2419 real_blkdev, errno, strerror(errno));
Paul Lawrence74f29f12014-08-28 15:54:10 -07002420 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002421 goto errout;
2422 }
2423
2424 if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002425 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
JP Abgrall77768712014-10-10 15:52:11 -07002426 crypto_blkdev, errno, strerror(errno));
JP Abgrall512f0d52014-10-10 18:43:41 -07002427 rc = ENABLE_INPLACE_ERR_DEV;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002428 goto errout;
2429 }
2430
2431 if (setjmp(setjmp_env)) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002432 SLOGE("Reading ext4 extent caused an exception\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002433 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002434 goto errout;
2435 }
2436
2437 if (read_ext(data.realfd, 0) != 0) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002438 SLOGE("Failed to read ext4 extent\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002439 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002440 goto errout;
2441 }
2442
2443 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2444 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2445 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2446
JP Abgrall512f0d52014-10-10 18:43:41 -07002447 SLOGI("Encrypting ext4 filesystem in place...");
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002448
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002449 data.tot_used_blocks = data.numblocks;
2450 for (i = 0; i < aux_info.groups; ++i) {
2451 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2452 }
2453
2454 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002455 data.cur_pct = 0;
Paul Lawrence9c58a872014-09-30 09:12:51 -07002456
2457 struct timespec time_started = {0};
2458 if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
2459 SLOGW("Error getting time at start");
2460 // Note - continue anyway - we'll run with 0
2461 }
2462 data.time_started = time_started.tv_sec;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002463 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002464
2465 rc = encrypt_groups(&data);
2466 if (rc) {
2467 SLOGE("Error encrypting groups");
2468 goto errout;
2469 }
2470
Paul Lawrence87999172014-02-20 12:21:31 -08002471 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002472 rc = 0;
2473
2474errout:
2475 close(data.realfd);
2476 close(data.cryptofd);
2477
2478 return rc;
2479}
2480
Paul Lawrence3846be12014-09-22 11:33:54 -07002481static void log_progress_f2fs(u64 block, bool completed)
2482{
2483 // Precondition - if completed data = 0 else data != 0
2484
2485 // Track progress so we can skip logging blocks
2486 static u64 last_block = (u64)-1;
2487
2488 // Need to close existing 'Encrypting from' log?
2489 if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
2490 SLOGI("Encrypted to block %" PRId64, last_block);
2491 last_block = -1;
2492 }
2493
2494 // Need to start new 'Encrypting from' log?
2495 if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
2496 SLOGI("Encrypting from block %" PRId64, block);
2497 }
2498
2499 // Update offset
2500 if (!completed) {
2501 last_block = block;
2502 }
2503}
2504
Daniel Rosenberge82df162014-08-15 22:19:23 +00002505static int encrypt_one_block_f2fs(u64 pos, void *data)
2506{
2507 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2508
2509 priv_dat->blocks_already_done = pos - 1;
2510 update_progress(priv_dat, 1);
2511
2512 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2513
2514 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002515 SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002516 return -1;
2517 }
2518
2519 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002520 SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002521 return -1;
2522 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002523 log_progress_f2fs(pos, false);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002524 }
2525
2526 return 0;
2527}
2528
2529static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2530 char *real_blkdev,
2531 off64_t size,
2532 off64_t *size_already_done,
2533 off64_t tot_size,
2534 off64_t previously_encrypted_upto)
2535{
Daniel Rosenberge82df162014-08-15 22:19:23 +00002536 struct encryptGroupsData data;
2537 struct f2fs_info *f2fs_info = NULL;
JP Abgrall512f0d52014-10-10 18:43:41 -07002538 int rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002539 if (previously_encrypted_upto > *size_already_done) {
2540 SLOGD("Not fast encrypting since resuming part way through");
JP Abgrall512f0d52014-10-10 18:43:41 -07002541 return ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002542 }
2543 memset(&data, 0, sizeof(data));
2544 data.real_blkdev = real_blkdev;
2545 data.crypto_blkdev = crypto_blkdev;
2546 data.realfd = -1;
2547 data.cryptofd = -1;
2548 if ( (data.realfd = open64(real_blkdev, O_RDWR)) < 0) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002549 SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
Daniel Rosenberge82df162014-08-15 22:19:23 +00002550 real_blkdev);
2551 goto errout;
2552 }
2553 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002554 SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
JP Abgrall77768712014-10-10 15:52:11 -07002555 crypto_blkdev, errno, strerror(errno));
JP Abgrall512f0d52014-10-10 18:43:41 -07002556 rc = ENABLE_INPLACE_ERR_DEV;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002557 goto errout;
2558 }
2559
2560 f2fs_info = generate_f2fs_info(data.realfd);
2561 if (!f2fs_info)
2562 goto errout;
2563
2564 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2565 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2566 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2567
2568 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2569
2570 data.one_pct = data.tot_used_blocks / 100;
2571 data.cur_pct = 0;
2572 data.time_started = time(NULL);
2573 data.remaining_time = -1;
2574
2575 data.buffer = malloc(f2fs_info->block_size);
2576 if (!data.buffer) {
2577 SLOGE("Failed to allocate crypto buffer");
2578 goto errout;
2579 }
2580
2581 data.count = 0;
2582
2583 /* Currently, this either runs to completion, or hits a nonrecoverable error */
2584 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2585
2586 if (rc) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002587 SLOGE("Error in running over f2fs blocks");
2588 rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002589 goto errout;
2590 }
2591
2592 *size_already_done += size;
2593 rc = 0;
2594
2595errout:
2596 if (rc)
2597 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2598
Paul Lawrence3846be12014-09-22 11:33:54 -07002599 log_progress_f2fs(0, true);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002600 free(f2fs_info);
2601 free(data.buffer);
2602 close(data.realfd);
2603 close(data.cryptofd);
2604
2605 return rc;
2606}
2607
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002608static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2609 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002610 off64_t tot_size,
2611 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002612{
2613 int realfd, cryptofd;
2614 char *buf[CRYPT_INPLACE_BUFSIZE];
JP Abgrall512f0d52014-10-10 18:43:41 -07002615 int rc = ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002616 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002617 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002618 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002619
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002620 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
2621 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
JP Abgrall512f0d52014-10-10 18:43:41 -07002622 return ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002623 }
2624
2625 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall77768712014-10-10 15:52:11 -07002626 SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
2627 crypto_blkdev, errno, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002628 close(realfd);
JP Abgrall512f0d52014-10-10 18:43:41 -07002629 return ENABLE_INPLACE_ERR_DEV;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002630 }
2631
2632 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2633 * The size passed in is the number of 512 byte sectors in the filesystem.
2634 * So compute the number of whole 4K blocks we should read/write,
2635 * and the remainder.
2636 */
2637 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2638 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002639 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2640 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002641
2642 SLOGE("Encrypting filesystem in place...");
2643
Paul Lawrence87999172014-02-20 12:21:31 -08002644 i = previously_encrypted_upto + 1 - *size_already_done;
2645
2646 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2647 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2648 goto errout;
2649 }
2650
2651 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2652 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2653 goto errout;
2654 }
2655
2656 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2657 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2658 SLOGE("Error reading initial sectors from real_blkdev %s for "
2659 "inplace encrypt\n", crypto_blkdev);
2660 goto errout;
2661 }
2662 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2663 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2664 "inplace encrypt\n", crypto_blkdev);
2665 goto errout;
2666 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002667 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002668 }
2669 }
2670
Ken Sumrall29d8da82011-05-18 17:20:07 -07002671 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002672 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002673 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002674 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002675 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002676 if (new_pct > cur_pct) {
2677 char buf[8];
2678
2679 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002680 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002681 property_set("vold.encrypt_progress", buf);
2682 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002683 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002684 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002685 goto errout;
2686 }
2687 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002688 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2689 goto errout;
2690 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002691 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002692 CRYPT_SECTORS_PER_BUFSIZE,
2693 i * CRYPT_SECTORS_PER_BUFSIZE);
2694 }
2695
Paul Lawrence73d7a022014-06-09 14:10:09 -07002696 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002697 SLOGE("Stopping encryption due to low battery");
2698 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2699 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002700 goto errout;
2701 }
2702 }
2703
2704 /* Do any remaining sectors */
2705 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002706 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2707 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002708 goto errout;
2709 }
Paul Lawrence87999172014-02-20 12:21:31 -08002710 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2711 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002712 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002713 } else {
2714 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002715 }
2716 }
2717
Ken Sumrall29d8da82011-05-18 17:20:07 -07002718 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002719 rc = 0;
2720
2721errout:
2722 close(realfd);
2723 close(cryptofd);
2724
2725 return rc;
2726}
2727
JP Abgrall512f0d52014-10-10 18:43:41 -07002728/* returns on of the ENABLE_INPLACE_* return codes */
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002729static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2730 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002731 off64_t tot_size,
2732 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002733{
JP Abgrall512f0d52014-10-10 18:43:41 -07002734 int rc_ext4, rc_f2fs, rc_full;
Paul Lawrence87999172014-02-20 12:21:31 -08002735 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002736 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002737 }
2738
2739 if (*size_already_done + size < previously_encrypted_upto) {
2740 *size_already_done += size;
2741 return 0;
2742 }
2743
Daniel Rosenberge82df162014-08-15 22:19:23 +00002744 /* TODO: identify filesystem type.
2745 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2746 * then we will drop down to cryptfs_enable_inplace_f2fs.
2747 * */
JP Abgrall512f0d52014-10-10 18:43:41 -07002748 if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002749 size, size_already_done,
JP Abgrall512f0d52014-10-10 18:43:41 -07002750 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002751 return 0;
2752 }
JP Abgrall512f0d52014-10-10 18:43:41 -07002753 SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002754
JP Abgrall512f0d52014-10-10 18:43:41 -07002755 if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002756 size, size_already_done,
JP Abgrall512f0d52014-10-10 18:43:41 -07002757 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002758 return 0;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002759 }
JP Abgrall512f0d52014-10-10 18:43:41 -07002760 SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002761
JP Abgrall512f0d52014-10-10 18:43:41 -07002762 rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002763 size, size_already_done, tot_size,
2764 previously_encrypted_upto);
JP Abgrall512f0d52014-10-10 18:43:41 -07002765 SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
2766
2767 /* Hack for b/17898962, the following is the symptom... */
2768 if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
2769 && rc_f2fs == ENABLE_INPLACE_ERR_DEV
2770 && rc_full == ENABLE_INPLACE_ERR_DEV) {
2771 return ENABLE_INPLACE_ERR_DEV;
2772 }
2773 return rc_full;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002774}
2775
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002776#define CRYPTO_ENABLE_WIPE 1
2777#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002778
2779#define FRAMEWORK_BOOT_WAIT 60
2780
Ken Sumrall29d8da82011-05-18 17:20:07 -07002781static inline int should_encrypt(struct volume_info *volume)
2782{
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002783 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
Ken Sumrall29d8da82011-05-18 17:20:07 -07002784 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
2785}
2786
Paul Lawrence87999172014-02-20 12:21:31 -08002787static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2788{
2789 int fd = open(filename, O_RDONLY);
2790 if (fd == -1) {
2791 SLOGE("Error opening file %s", filename);
2792 return -1;
2793 }
2794
2795 char block[CRYPT_INPLACE_BUFSIZE];
2796 memset(block, 0, sizeof(block));
2797 if (unix_read(fd, block, sizeof(block)) < 0) {
2798 SLOGE("Error reading file %s", filename);
2799 close(fd);
2800 return -1;
2801 }
2802
2803 close(fd);
2804
2805 SHA256_CTX c;
2806 SHA256_Init(&c);
2807 SHA256_Update(&c, block, sizeof(block));
2808 SHA256_Final(buf, &c);
2809
2810 return 0;
2811}
2812
JP Abgrall62c7af32014-06-16 13:01:23 -07002813static int get_fs_type(struct fstab_rec *rec)
2814{
2815 if (!strcmp(rec->fs_type, "ext4")) {
2816 return EXT4_FS;
2817 } else if (!strcmp(rec->fs_type, "f2fs")) {
2818 return F2FS_FS;
2819 } else {
2820 return -1;
2821 }
2822}
2823
Paul Lawrence87999172014-02-20 12:21:31 -08002824static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2825 char *crypto_blkdev, char *real_blkdev,
2826 int previously_encrypted_upto)
2827{
2828 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002829 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002830
Paul Lawrence73d7a022014-06-09 14:10:09 -07002831 if (!is_battery_ok_to_start()) {
2832 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002833 return 0;
2834 }
2835
2836 /* The size of the userdata partition, and add in the vold volumes below */
2837 tot_encryption_size = crypt_ftr->fs_size;
2838
2839 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002840 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2841 int fs_type = get_fs_type(rec);
2842 if (fs_type < 0) {
2843 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2844 return -1;
2845 }
2846 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002847 } else if (how == CRYPTO_ENABLE_INPLACE) {
2848 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2849 crypt_ftr->fs_size, &cur_encryption_done,
2850 tot_encryption_size,
2851 previously_encrypted_upto);
2852
JP Abgrall512f0d52014-10-10 18:43:41 -07002853 if (rc == ENABLE_INPLACE_ERR_DEV) {
2854 /* Hack for b/17898962 */
2855 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2856 cryptfs_reboot(reboot);
2857 }
2858
Paul Lawrence73d7a022014-06-09 14:10:09 -07002859 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002860 crypt_ftr->encrypted_upto = cur_encryption_done;
2861 }
2862
Paul Lawrence73d7a022014-06-09 14:10:09 -07002863 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002864 /* The inplace routine never actually sets the progress to 100% due
2865 * to the round down nature of integer division, so set it here */
2866 property_set("vold.encrypt_progress", "100");
2867 }
2868 } else {
2869 /* Shouldn't happen */
2870 SLOGE("cryptfs_enable: internal error, unknown option\n");
2871 rc = -1;
2872 }
2873
2874 return rc;
2875}
2876
Paul Lawrence13486032014-02-03 13:28:11 -08002877int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
2878 int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002879{
2880 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002881 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07002882 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002883 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Tim Murray8439dc92014-12-15 11:56:11 -08002884 int rc=-1, fd, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002885 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002886 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002887 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002888 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002889 char key_loc[PROPERTY_VALUE_MAX];
2890 char fuse_sdcard[PROPERTY_VALUE_MAX];
2891 char *sd_mnt_point;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002892 int num_vols;
2893 struct volume_info *vol_list = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002894 off64_t previously_encrypted_upto = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002895
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002896 if (!strcmp(howarg, "wipe")) {
2897 how = CRYPTO_ENABLE_WIPE;
2898 } else if (! strcmp(howarg, "inplace")) {
2899 how = CRYPTO_ENABLE_INPLACE;
2900 } else {
2901 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002902 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002903 }
2904
Paul Lawrence87999172014-02-20 12:21:31 -08002905 /* See if an encryption was underway and interrupted */
2906 if (how == CRYPTO_ENABLE_INPLACE
2907 && get_crypt_ftr_and_key(&crypt_ftr) == 0
2908 && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
2909 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2910 crypt_ftr.encrypted_upto = 0;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002911 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
2912
2913 /* At this point, we are in an inconsistent state. Until we successfully
2914 complete encryption, a reboot will leave us broken. So mark the
2915 encryption failed in case that happens.
2916 On successfully completing encryption, remove this flag */
2917 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2918
2919 put_crypt_ftr_and_key(&crypt_ftr);
Paul Lawrence87999172014-02-20 12:21:31 -08002920 }
2921
2922 property_get("ro.crypto.state", encrypted_state, "");
2923 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2924 SLOGE("Device is already running encrypted, aborting");
2925 goto error_unencrypted;
2926 }
2927
2928 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2929 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002930 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002931
Ken Sumrall3ed82362011-01-28 23:31:16 -08002932 /* Get the size of the real block device */
2933 fd = open(real_blkdev, O_RDONLY);
2934 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
2935 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2936 goto error_unencrypted;
2937 }
2938 close(fd);
2939
2940 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002941 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002942 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002943 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002944 if (fs_size_sec == 0)
2945 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2946
Paul Lawrence87999172014-02-20 12:21:31 -08002947 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002948
2949 if (fs_size_sec > max_fs_size_sec) {
2950 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2951 goto error_unencrypted;
2952 }
2953 }
2954
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002955 /* Get a wakelock as this may take a while, and we don't want the
2956 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2957 * wants to keep the screen on, it can grab a full wakelock.
2958 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002959 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002960 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2961
Jeff Sharkey7382f812012-08-23 14:08:59 -07002962 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07002963 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07002964 if (!sd_mnt_point) {
2965 sd_mnt_point = getenv("EXTERNAL_STORAGE");
2966 }
2967 if (!sd_mnt_point) {
2968 sd_mnt_point = "/mnt/sdcard";
2969 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07002970
Paul Lawrence87999172014-02-20 12:21:31 -08002971 /* TODO
2972 * Currently do not have test devices with multiple encryptable volumes.
2973 * When we acquire some, re-add support.
2974 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002975 num_vols=vold_getNumDirectVolumes();
2976 vol_list = malloc(sizeof(struct volume_info) * num_vols);
2977 vold_getDirectVolumeList(vol_list);
2978
2979 for (i=0; i<num_vols; i++) {
2980 if (should_encrypt(&vol_list[i])) {
Paul Lawrence87999172014-02-20 12:21:31 -08002981 SLOGE("Cannot encrypt if there are multiple encryptable volumes"
2982 "%s\n", vol_list[i].label);
2983 goto error_unencrypted;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002984 }
2985 }
2986
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002987 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002988 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002989 */
2990 property_set("vold.decrypt", "trigger_shutdown_framework");
2991 SLOGD("Just asked init to shut down class main\n");
2992
Ken Sumrall425524d2012-06-14 20:55:28 -07002993 if (vold_unmountAllAsecs()) {
2994 /* Just report the error. If any are left mounted,
2995 * umounting /data below will fail and handle the error.
2996 */
2997 SLOGE("Error unmounting internal asecs");
2998 }
2999
Ken Sumrall29d8da82011-05-18 17:20:07 -07003000 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
3001 if (!strcmp(fuse_sdcard, "true")) {
3002 /* This is a device using the fuse layer to emulate the sdcard semantics
3003 * on top of the userdata partition. vold does not manage it, it is managed
3004 * by the sdcard service. The sdcard service was killed by the property trigger
3005 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
3006 * unlike the case for vold managed devices above.
3007 */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07003008 if (wait_and_unmount(sd_mnt_point, false)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07003009 goto error_shutting_down;
3010 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08003011 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003012
3013 /* Now unmount the /data partition. */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07003014 if (wait_and_unmount(DATA_MNT_POINT, false)) {
JP Abgrall502dc742013-11-01 13:06:20 -07003015 if (allow_reboot) {
3016 goto error_shutting_down;
3017 } else {
3018 goto error_unencrypted;
3019 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003020 }
3021
3022 /* Do extra work for a better UX when doing the long inplace encryption */
3023 if (how == CRYPTO_ENABLE_INPLACE) {
3024 /* Now that /data is unmounted, we need to mount a tmpfs
3025 * /data, set a property saying we're doing inplace encryption,
3026 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003027 */
Ken Sumralle5032c42012-04-01 23:58:44 -07003028 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003029 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003030 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003031 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08003032 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003033
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003034 /* restart the framework. */
3035 /* Create necessary paths on /data */
3036 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003037 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003038 }
3039
Ken Sumrall92736ef2012-10-17 20:57:14 -07003040 /* Ugh, shutting down the framework is not synchronous, so until it
3041 * can be fixed, this horrible hack will wait a moment for it all to
3042 * shut down before proceeding. Without it, some devices cannot
3043 * restart the graphics services.
3044 */
3045 sleep(2);
3046
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003047 /* startup service classes main and late_start */
3048 property_set("vold.decrypt", "trigger_restart_min_framework");
3049 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003050
Ken Sumrall7df84122011-01-18 14:04:08 -08003051 /* OK, the framework is restarted and will soon be showing a
3052 * progress bar. Time to setup an encrypted mapping, and
3053 * either write a new filesystem, or encrypt in place updating
3054 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003055 */
3056 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003057
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003058 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003059 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence87999172014-02-20 12:21:31 -08003060 if (previously_encrypted_upto == 0) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07003061 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
3062 goto error_shutting_down;
3063 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003064
Paul Lawrence87999172014-02-20 12:21:31 -08003065 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
3066 crypt_ftr.fs_size = nr_sec
3067 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
3068 } else {
3069 crypt_ftr.fs_size = nr_sec;
3070 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07003071 /* At this point, we are in an inconsistent state. Until we successfully
3072 complete encryption, a reboot will leave us broken. So mark the
3073 encryption failed in case that happens.
3074 On successfully completing encryption, remove this flag */
3075 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence87999172014-02-20 12:21:31 -08003076 crypt_ftr.crypt_type = crypt_type;
3077 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003078
Paul Lawrence87999172014-02-20 12:21:31 -08003079 /* Make an encrypted master key */
3080 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
3081 SLOGE("Cannot create encrypted master key\n");
3082 goto error_shutting_down;
3083 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003084
Paul Lawrence87999172014-02-20 12:21:31 -08003085 /* Write the key to the end of the partition */
3086 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003087
Paul Lawrence87999172014-02-20 12:21:31 -08003088 /* If any persistent data has been remembered, save it.
3089 * If none, create a valid empty table and save that.
3090 */
3091 if (!persist_data) {
3092 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
3093 if (pdata) {
3094 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
3095 persist_data = pdata;
3096 }
3097 }
3098 if (persist_data) {
3099 save_persistent_data();
3100 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003101 }
3102
Paul Lawrenced0c7b172014-08-08 14:28:10 -07003103 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07003104 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
3105 "userdata");
3106
Paul Lawrence87999172014-02-20 12:21:31 -08003107 /* If we are continuing, check checksums match */
3108 rc = 0;
3109 if (previously_encrypted_upto) {
3110 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
3111 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07003112
Paul Lawrence87999172014-02-20 12:21:31 -08003113 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
3114 sizeof(hash_first_block)) != 0) {
3115 SLOGE("Checksums do not match - trigger wipe");
3116 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003117 }
3118 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003119
Paul Lawrence87999172014-02-20 12:21:31 -08003120 if (!rc) {
3121 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
3122 crypto_blkdev, real_blkdev,
3123 previously_encrypted_upto);
3124 }
3125
3126 /* Calculate checksum if we are not finished */
Paul Lawrence73d7a022014-06-09 14:10:09 -07003127 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003128 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
3129 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07003130 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08003131 SLOGE("Error calculating checksum for continuing encryption");
3132 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003133 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003134 }
3135
3136 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003137 delete_crypto_blk_dev("userdata");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003138
3139 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003140
3141 if (! rc) {
3142 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003143 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08003144
Paul Lawrence6bfed202014-07-28 12:47:22 -07003145 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003146 SLOGD("Encrypted up to sector %lld - will continue after reboot",
3147 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07003148 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08003149 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07003150
Paul Lawrence6bfed202014-07-28 12:47:22 -07003151 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08003152
Paul Lawrence73d7a022014-06-09 14:10:09 -07003153 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003154 char value[PROPERTY_VALUE_MAX];
3155 property_get("ro.crypto.state", value, "");
3156 if (!strcmp(value, "")) {
3157 /* default encryption - continue first boot sequence */
3158 property_set("ro.crypto.state", "encrypted");
3159 release_wake_lock(lockid);
3160 cryptfs_check_passwd(DEFAULT_PASSWORD);
3161 cryptfs_restart_internal(1);
3162 return 0;
3163 } else {
3164 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08003165 cryptfs_reboot(reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003166 }
Paul Lawrence87999172014-02-20 12:21:31 -08003167 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003168 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Paul Lawrence87999172014-02-20 12:21:31 -08003169 cryptfs_reboot(shutdown);
3170 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003171 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003172 char value[PROPERTY_VALUE_MAX];
3173
Ken Sumrall319369a2012-06-27 16:30:18 -07003174 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003175 if (!strcmp(value, "1")) {
3176 /* wipe data if encryption failed */
3177 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
3178 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07003179 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003180 if (fd >= 0) {
Jeff Sharkeydd1a8042014-09-24 11:46:51 -07003181 write(fd, "--wipe_data\n", strlen("--wipe_data\n") + 1);
3182 write(fd, "--reason=cryptfs_enable_internal\n", strlen("--reason=cryptfs_enable_internal\n") + 1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003183 close(fd);
3184 } else {
3185 SLOGE("could not open /cache/recovery/command\n");
3186 }
Paul Lawrence87999172014-02-20 12:21:31 -08003187 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003188 } else {
3189 /* set property to trigger dialog */
3190 property_set("vold.encrypt_progress", "error_partially_encrypted");
3191 release_wake_lock(lockid);
3192 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003193 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003194 }
3195
Ken Sumrall3ed82362011-01-28 23:31:16 -08003196 /* hrm, the encrypt step claims success, but the reboot failed.
3197 * This should not happen.
3198 * Set the property and return. Hope the framework can deal with it.
3199 */
3200 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003201 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003202 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08003203
3204error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07003205 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003206 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003207 if (lockid[0]) {
3208 release_wake_lock(lockid);
3209 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003210 return -1;
3211
3212error_shutting_down:
3213 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3214 * but the framework is stopped and not restarted to show the error, so it's up to
3215 * vold to restart the system.
3216 */
3217 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08003218 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003219
3220 /* shouldn't get here */
3221 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003222 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003223 if (lockid[0]) {
3224 release_wake_lock(lockid);
3225 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003226 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003227}
3228
Paul Lawrence45f10532014-04-04 18:11:56 +00003229int cryptfs_enable(char *howarg, int type, char *passwd, int allow_reboot)
Paul Lawrence13486032014-02-03 13:28:11 -08003230{
Paul Lawrencefc615042014-10-04 15:32:29 -07003231 char* adjusted_passwd = adjust_passwd(passwd);
3232 if (adjusted_passwd) {
3233 passwd = adjusted_passwd;
3234 }
3235
3236 int rc = cryptfs_enable_internal(howarg, type, passwd, allow_reboot);
3237
3238 free(adjusted_passwd);
3239 return rc;
Paul Lawrence13486032014-02-03 13:28:11 -08003240}
3241
3242int cryptfs_enable_default(char *howarg, int allow_reboot)
3243{
3244 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
3245 DEFAULT_PASSWORD, allow_reboot);
3246}
3247
Paul Lawrencec19cb9c2015-01-21 09:58:26 -08003248static int device_is_force_encrypted() {
3249 int ret = -1;
3250 char value[PROP_VALUE_MAX];
3251 ret = __system_property_get("ro.vold.forceencryption", value);
3252 if (ret < 0)
3253 return 0;
3254 return strcmp(value, "1") ? 0 : 1;
3255}
3256
3257int cryptfs_maybe_enable_default_crypto()
3258{
3259 // Enable default crypt if /forceencrypt or /encryptable and
3260 // ro.vold.forceencrypt=1, else mount data and continue unencrypted
3261 struct fstab_rec *fstab_rec = 0;
3262 fstab_rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
3263 if (!fstab_rec) {
3264 SLOGE("Error getting fstab record");
3265 return -1;
3266 }
3267
3268 // See if we should encrypt?
3269 if ( !fs_mgr_is_encryptable(fstab_rec)
3270 || (!fs_mgr_is_force_encrypted(fstab_rec)
3271 && !device_is_force_encrypted())) {
3272 int rc = 0;
3273
3274 rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT, fstab_rec->blk_device, 0);
3275 property_set("vold.decrypt", "trigger_load_persist_props");
3276
3277 /* Create necessary paths on /data */
3278 if (prep_data_fs()) {
3279 return -1;
3280 }
3281
3282 property_set("ro.crypto.state", "unencrypted");
3283 property_set("vold.decrypt", "trigger_restart_framework");
3284 SLOGD("Unencrypted - restart_framework\n");
3285 return rc;
3286 }
3287
3288 return cryptfs_enable_default("inplace", 0);
3289}
3290
Paul Lawrence13486032014-02-03 13:28:11 -08003291int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003292{
3293 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003294
3295 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003296 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003297 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003298 return -1;
3299 }
3300
Paul Lawrencef4faa572014-01-29 13:31:03 -08003301 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3302 SLOGE("Invalid crypt_type %d", crypt_type);
3303 return -1;
3304 }
3305
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003306 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003307 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003308 SLOGE("Error getting crypt footer and key");
3309 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003310 }
3311
Paul Lawrencef4faa572014-01-29 13:31:03 -08003312 crypt_ftr.crypt_type = crypt_type;
3313
Paul Lawrencefc615042014-10-04 15:32:29 -07003314 char* adjusted_passwd = adjust_passwd(newpw);
3315 if (adjusted_passwd) {
3316 newpw = adjusted_passwd;
3317 }
3318
Paul Lawrencef4faa572014-01-29 13:31:03 -08003319 encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
3320 : newpw,
3321 crypt_ftr.salt,
3322 saved_master_key,
3323 crypt_ftr.master_key,
3324 &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003325
Jason parks70a4b3f2011-01-28 10:10:47 -06003326 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003327 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003328
Paul Lawrencefc615042014-10-04 15:32:29 -07003329 free(adjusted_passwd);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003330 return 0;
3331}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003332
3333static int persist_get_key(char *fieldname, char *value)
3334{
3335 unsigned int i;
3336
3337 if (persist_data == NULL) {
3338 return -1;
3339 }
3340 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3341 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3342 /* We found it! */
3343 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3344 return 0;
3345 }
3346 }
3347
3348 return -1;
3349}
3350
3351static int persist_set_key(char *fieldname, char *value, int encrypted)
3352{
3353 unsigned int i;
3354 unsigned int num;
3355 struct crypt_mnt_ftr crypt_ftr;
3356 unsigned int max_persistent_entries;
3357 unsigned int dsize;
3358
3359 if (persist_data == NULL) {
3360 return -1;
3361 }
3362
3363 /* If encrypted, use the values from the crypt_ftr, otherwise
3364 * use the values for the current spec.
3365 */
3366 if (encrypted) {
3367 if(get_crypt_ftr_and_key(&crypt_ftr)) {
3368 return -1;
3369 }
3370 dsize = crypt_ftr.persist_data_size;
3371 } else {
3372 dsize = CRYPT_PERSIST_DATA_SIZE;
3373 }
3374 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3375 sizeof(struct crypt_persist_entry);
3376
3377 num = persist_data->persist_valid_entries;
3378
3379 for (i = 0; i < num; i++) {
3380 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3381 /* We found an existing entry, update it! */
3382 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3383 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3384 return 0;
3385 }
3386 }
3387
3388 /* We didn't find it, add it to the end, if there is room */
3389 if (persist_data->persist_valid_entries < max_persistent_entries) {
3390 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3391 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3392 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3393 persist_data->persist_valid_entries++;
3394 return 0;
3395 }
3396
3397 return -1;
3398}
3399
3400/* Return the value of the specified field. */
3401int cryptfs_getfield(char *fieldname, char *value, int len)
3402{
3403 char temp_value[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003404 /* 0 is success, 1 is not encrypted,
3405 * -1 is value not set, -2 is any other error
3406 */
3407 int rc = -2;
3408
3409 if (persist_data == NULL) {
3410 load_persistent_data();
3411 if (persist_data == NULL) {
3412 SLOGE("Getfield error, cannot load persistent data");
3413 goto out;
3414 }
3415 }
3416
3417 if (!persist_get_key(fieldname, temp_value)) {
3418 /* We found it, copy it to the caller's buffer and return */
3419 strlcpy(value, temp_value, len);
3420 rc = 0;
3421 } else {
3422 /* Sadness, it's not there. Return the error */
3423 rc = -1;
3424 }
3425
3426out:
3427 return rc;
3428}
3429
3430/* Set the value of the specified field. */
3431int cryptfs_setfield(char *fieldname, char *value)
3432{
Ken Sumrall160b4d62013-04-22 12:15:39 -07003433 char encrypted_state[PROPERTY_VALUE_MAX];
3434 /* 0 is success, -1 is an error */
3435 int rc = -1;
3436 int encrypted = 0;
3437
3438 if (persist_data == NULL) {
3439 load_persistent_data();
3440 if (persist_data == NULL) {
3441 SLOGE("Setfield error, cannot load persistent data");
3442 goto out;
3443 }
3444 }
3445
3446 property_get("ro.crypto.state", encrypted_state, "");
3447 if (!strcmp(encrypted_state, "encrypted") ) {
3448 encrypted = 1;
3449 }
3450
3451 if (persist_set_key(fieldname, value, encrypted)) {
3452 goto out;
3453 }
3454
3455 /* If we are running encrypted, save the persistent data now */
3456 if (encrypted) {
3457 if (save_persistent_data()) {
3458 SLOGE("Setfield error, cannot save persistent data");
3459 goto out;
3460 }
3461 }
3462
3463 rc = 0;
3464
3465out:
3466 return rc;
3467}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003468
3469/* Checks userdata. Attempt to mount the volume if default-
3470 * encrypted.
3471 * On success trigger next init phase and return 0.
3472 * Currently do not handle failure - see TODO below.
3473 */
3474int cryptfs_mount_default_encrypted(void)
3475{
3476 char decrypt_state[PROPERTY_VALUE_MAX];
3477 property_get("vold.decrypt", decrypt_state, "0");
3478 if (!strcmp(decrypt_state, "0")) {
3479 SLOGE("Not encrypted - should not call here");
3480 } else {
3481 int crypt_type = cryptfs_get_password_type();
3482 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3483 SLOGE("Bad crypt type - error");
3484 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3485 SLOGD("Password is not default - "
3486 "starting min framework to prompt");
3487 property_set("vold.decrypt", "trigger_restart_min_framework");
3488 return 0;
3489 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3490 SLOGD("Password is default - restarting filesystem");
3491 cryptfs_restart_internal(0);
3492 return 0;
3493 } else {
3494 SLOGE("Encrypted, default crypt type but can't decrypt");
3495 }
3496 }
3497
Paul Lawrence6bfed202014-07-28 12:47:22 -07003498 /** Corrupt. Allow us to boot into framework, which will detect bad
3499 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003500 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003501 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003502 return 0;
3503}
3504
3505/* Returns type of the password, default, pattern, pin or password.
3506 */
3507int cryptfs_get_password_type(void)
3508{
3509 struct crypt_mnt_ftr crypt_ftr;
3510
3511 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3512 SLOGE("Error getting crypt footer and key\n");
3513 return -1;
3514 }
3515
Paul Lawrence6bfed202014-07-28 12:47:22 -07003516 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3517 return -1;
3518 }
3519
Paul Lawrencef4faa572014-01-29 13:31:03 -08003520 return crypt_ftr.crypt_type;
3521}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003522
Paul Lawrence399317e2014-03-10 13:20:50 -07003523char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003524{
Paul Lawrence399317e2014-03-10 13:20:50 -07003525 struct timespec now;
3526 clock_gettime(CLOCK_MONOTONIC, &now);
3527 if (now.tv_sec < password_expiry_time) {
3528 return password;
3529 } else {
3530 cryptfs_clear_password();
3531 return 0;
3532 }
3533}
3534
3535void cryptfs_clear_password()
3536{
3537 if (password) {
3538 size_t len = strlen(password);
3539 memset(password, 0, len);
3540 free(password);
3541 password = 0;
3542 password_expiry_time = 0;
3543 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003544}