blob: 8747540c2c22255690dbf6bbc4ee2c7be155ded1 [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");
571 return;
572 }
573 /* Write all zeros to the first copy, making it invalid */
574 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
575
576 /* Write a valid but empty structure to the second copy */
577 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
578 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
579
580 /* Update the footer */
581 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
582 crypt_ftr->persist_data_offset[0] = pdata_offset;
583 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
584 crypt_ftr->minor_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700585 }
586
Paul Lawrencef4faa572014-01-29 13:31:03 -0800587 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700588 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800589 /* But keep the old kdf_type.
590 * It will get updated later to KDF_SCRYPT after the password has been verified.
591 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700592 crypt_ftr->kdf_type = KDF_PBKDF2;
593 get_device_scrypt_params(crypt_ftr);
594 crypt_ftr->minor_version = 2;
595 }
596
Paul Lawrencef4faa572014-01-29 13:31:03 -0800597 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
598 SLOGW("upgrading crypto footer to 1.3");
599 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
600 crypt_ftr->minor_version = 3;
601 }
602
Kenny Root7434b312013-06-14 11:29:53 -0700603 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
604 if (lseek64(fd, offset, SEEK_SET) == -1) {
605 SLOGE("Cannot seek to crypt footer\n");
606 return;
607 }
608 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700609 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700610}
611
612
613static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800614{
615 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800616 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700617 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800618 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700619 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700620 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800621
Ken Sumrall160b4d62013-04-22 12:15:39 -0700622 if (get_crypt_ftr_info(&fname, &starting_off)) {
623 SLOGE("Unable to get crypt_ftr_info\n");
624 return -1;
625 }
626 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700627 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700628 return -1;
629 }
630 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700631 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700632 return -1;
633 }
634
635 /* Make sure it's 16 Kbytes in length */
636 fstat(fd, &statbuf);
637 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
638 SLOGE("footer file %s is not the expected size!\n", fname);
639 goto errout;
640 }
641
642 /* Seek to the start of the crypt footer */
643 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
644 SLOGE("Cannot seek to real block device footer\n");
645 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800646 }
647
648 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
649 SLOGE("Cannot read real block device footer\n");
650 goto errout;
651 }
652
653 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700654 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800655 goto errout;
656 }
657
Kenny Rootc96a5f82013-06-14 12:08:28 -0700658 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
659 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
660 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800661 goto errout;
662 }
663
Kenny Rootc96a5f82013-06-14 12:08:28 -0700664 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
665 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
666 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800667 }
668
Ken Sumrall160b4d62013-04-22 12:15:39 -0700669 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
670 * copy on disk before returning.
671 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700672 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700673 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800674 }
675
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800676 /* Success! */
677 rc = 0;
678
679errout:
680 close(fd);
681 return rc;
682}
683
Ken Sumrall160b4d62013-04-22 12:15:39 -0700684static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
685{
686 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
687 crypt_ftr->persist_data_offset[1]) {
688 SLOGE("Crypt_ftr persist data regions overlap");
689 return -1;
690 }
691
692 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
693 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
694 return -1;
695 }
696
697 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
698 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
699 CRYPT_FOOTER_OFFSET) {
700 SLOGE("Persistent data extends past crypto footer");
701 return -1;
702 }
703
704 return 0;
705}
706
707static int load_persistent_data(void)
708{
709 struct crypt_mnt_ftr crypt_ftr;
710 struct crypt_persist_data *pdata = NULL;
711 char encrypted_state[PROPERTY_VALUE_MAX];
712 char *fname;
713 int found = 0;
714 int fd;
715 int ret;
716 int i;
717
718 if (persist_data) {
719 /* Nothing to do, we've already loaded or initialized it */
720 return 0;
721 }
722
723
724 /* If not encrypted, just allocate an empty table and initialize it */
725 property_get("ro.crypto.state", encrypted_state, "");
726 if (strcmp(encrypted_state, "encrypted") ) {
727 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
728 if (pdata) {
729 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
730 persist_data = pdata;
731 return 0;
732 }
733 return -1;
734 }
735
736 if(get_crypt_ftr_and_key(&crypt_ftr)) {
737 return -1;
738 }
739
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700740 if ((crypt_ftr.major_version < 1)
741 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700742 SLOGE("Crypt_ftr version doesn't support persistent data");
743 return -1;
744 }
745
746 if (get_crypt_ftr_info(&fname, NULL)) {
747 return -1;
748 }
749
750 ret = validate_persistent_data_storage(&crypt_ftr);
751 if (ret) {
752 return -1;
753 }
754
755 fd = open(fname, O_RDONLY);
756 if (fd < 0) {
757 SLOGE("Cannot open %s metadata file", fname);
758 return -1;
759 }
760
761 if (persist_data == NULL) {
762 pdata = malloc(crypt_ftr.persist_data_size);
763 if (pdata == NULL) {
764 SLOGE("Cannot allocate memory for persistent data");
765 goto err;
766 }
767 }
768
769 for (i = 0; i < 2; i++) {
770 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
771 SLOGE("Cannot seek to read persistent data on %s", fname);
772 goto err2;
773 }
774 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
775 SLOGE("Error reading persistent data on iteration %d", i);
776 goto err2;
777 }
778 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
779 found = 1;
780 break;
781 }
782 }
783
784 if (!found) {
785 SLOGI("Could not find valid persistent data, creating");
786 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
787 }
788
789 /* Success */
790 persist_data = pdata;
791 close(fd);
792 return 0;
793
794err2:
795 free(pdata);
796
797err:
798 close(fd);
799 return -1;
800}
801
802static int save_persistent_data(void)
803{
804 struct crypt_mnt_ftr crypt_ftr;
805 struct crypt_persist_data *pdata;
806 char *fname;
807 off64_t write_offset;
808 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700809 int fd;
810 int ret;
811
812 if (persist_data == NULL) {
813 SLOGE("No persistent data to save");
814 return -1;
815 }
816
817 if(get_crypt_ftr_and_key(&crypt_ftr)) {
818 return -1;
819 }
820
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700821 if ((crypt_ftr.major_version < 1)
822 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700823 SLOGE("Crypt_ftr version doesn't support persistent data");
824 return -1;
825 }
826
827 ret = validate_persistent_data_storage(&crypt_ftr);
828 if (ret) {
829 return -1;
830 }
831
832 if (get_crypt_ftr_info(&fname, NULL)) {
833 return -1;
834 }
835
836 fd = open(fname, O_RDWR);
837 if (fd < 0) {
838 SLOGE("Cannot open %s metadata file", fname);
839 return -1;
840 }
841
842 pdata = malloc(crypt_ftr.persist_data_size);
843 if (pdata == NULL) {
844 SLOGE("Cannot allocate persistant data");
845 goto err;
846 }
847
848 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
849 SLOGE("Cannot seek to read persistent data on %s", fname);
850 goto err2;
851 }
852
853 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
854 SLOGE("Error reading persistent data before save");
855 goto err2;
856 }
857
858 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
859 /* The first copy is the curent valid copy, so write to
860 * the second copy and erase this one */
861 write_offset = crypt_ftr.persist_data_offset[1];
862 erase_offset = crypt_ftr.persist_data_offset[0];
863 } else {
864 /* The second copy must be the valid copy, so write to
865 * the first copy, and erase the second */
866 write_offset = crypt_ftr.persist_data_offset[0];
867 erase_offset = crypt_ftr.persist_data_offset[1];
868 }
869
870 /* Write the new copy first, if successful, then erase the old copy */
871 if (lseek(fd, write_offset, SEEK_SET) < 0) {
872 SLOGE("Cannot seek to write persistent data");
873 goto err2;
874 }
875 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
876 (int) crypt_ftr.persist_data_size) {
877 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
878 SLOGE("Cannot seek to erase previous persistent data");
879 goto err2;
880 }
881 fsync(fd);
882 memset(pdata, 0, crypt_ftr.persist_data_size);
883 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
884 (int) crypt_ftr.persist_data_size) {
885 SLOGE("Cannot write to erase previous persistent data");
886 goto err2;
887 }
888 fsync(fd);
889 } else {
890 SLOGE("Cannot write to save persistent data");
891 goto err2;
892 }
893
894 /* Success */
895 free(pdata);
896 close(fd);
897 return 0;
898
899err2:
900 free(pdata);
901err:
902 close(fd);
903 return -1;
904}
905
Paul Lawrencef4faa572014-01-29 13:31:03 -0800906static int hexdigit (char c)
907{
908 if (c >= '0' && c <= '9') return c - '0';
909 c = tolower(c);
910 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
911 return -1;
912}
913
914static unsigned char* convert_hex_ascii_to_key(const char* master_key_ascii,
915 unsigned int* out_keysize)
916{
917 unsigned int i;
918 *out_keysize = 0;
919
920 size_t size = strlen (master_key_ascii);
921 if (size % 2) {
922 SLOGE("Trying to convert ascii string of odd length");
923 return NULL;
924 }
925
926 unsigned char* master_key = (unsigned char*) malloc(size / 2);
927 if (master_key == 0) {
928 SLOGE("Cannot allocate");
929 return NULL;
930 }
931
932 for (i = 0; i < size; i += 2) {
933 int high_nibble = hexdigit (master_key_ascii[i]);
934 int low_nibble = hexdigit (master_key_ascii[i + 1]);
935
936 if(high_nibble < 0 || low_nibble < 0) {
937 SLOGE("Invalid hex string");
938 free (master_key);
939 return NULL;
940 }
941
942 master_key[*out_keysize] = high_nibble * 16 + low_nibble;
943 (*out_keysize)++;
944 }
945
946 return master_key;
947}
948
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800949/* Convert a binary key of specified length into an ascii hex string equivalent,
950 * without the leading 0x and with null termination
951 */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800952static void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800953 char *master_key_ascii)
954{
955 unsigned int i, a;
956 unsigned char nibble;
957
958 for (i=0, a=0; i<keysize; i++, a+=2) {
959 /* For each byte, write out two ascii hex digits */
960 nibble = (master_key[i] >> 4) & 0xf;
961 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
962
963 nibble = master_key[i] & 0xf;
964 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
965 }
966
967 /* Add the null termination */
968 master_key_ascii[a] = '\0';
969
970}
971
Ken Sumralldb5e0262013-02-05 17:39:48 -0800972static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
973 char *real_blk_name, const char *name, int fd,
974 char *extra_params)
975{
Dan Albertc07fa3f2014-12-18 10:00:55 -0800976 _Alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800977 struct dm_ioctl *io;
978 struct dm_target_spec *tgt;
979 char *crypt_params;
980 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
981 int i;
982
983 io = (struct dm_ioctl *) buffer;
984
985 /* Load the mapping table for this device */
986 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
987
988 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
989 io->target_count = 1;
990 tgt->status = 0;
991 tgt->sector_start = 0;
992 tgt->length = crypt_ftr->fs_size;
993 strcpy(tgt->target_type, "crypt");
994
995 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
996 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
997 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
998 master_key_ascii, real_blk_name, extra_params);
999 crypt_params += strlen(crypt_params) + 1;
1000 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1001 tgt->next = crypt_params - buffer;
1002
1003 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1004 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
1005 break;
1006 }
1007 usleep(500000);
1008 }
1009
1010 if (i == TABLE_LOAD_RETRIES) {
1011 /* We failed to load the table, return an error */
1012 return -1;
1013 } else {
1014 return i + 1;
1015 }
1016}
1017
1018
1019static int get_dm_crypt_version(int fd, const char *name, int *version)
1020{
1021 char buffer[DM_CRYPT_BUF_SIZE];
1022 struct dm_ioctl *io;
1023 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001024
1025 io = (struct dm_ioctl *) buffer;
1026
1027 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1028
1029 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1030 return -1;
1031 }
1032
1033 /* Iterate over the returned versions, looking for name of "crypt".
1034 * When found, get and return the version.
1035 */
1036 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1037 while (v->next) {
1038 if (! strcmp(v->name, "crypt")) {
1039 /* We found the crypt driver, return the version, and get out */
1040 version[0] = v->version[0];
1041 version[1] = v->version[1];
1042 version[2] = v->version[2];
1043 return 0;
1044 }
1045 v = (struct dm_target_versions *)(((char *)v) + v->next);
1046 }
1047
1048 return -1;
1049}
1050
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001051static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -07001052 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001053{
1054 char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001055 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001056 unsigned int minor;
1057 int fd;
1058 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001059 int version[3];
1060 char *extra_params;
1061 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001062
1063 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1064 SLOGE("Cannot open device-mapper\n");
1065 goto errout;
1066 }
1067
1068 io = (struct dm_ioctl *) buffer;
1069
1070 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1071 if (ioctl(fd, DM_DEV_CREATE, io)) {
1072 SLOGE("Cannot create dm-crypt device\n");
1073 goto errout;
1074 }
1075
1076 /* Get the device status, in particular, the name of it's device file */
1077 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1078 if (ioctl(fd, DM_DEV_STATUS, io)) {
1079 SLOGE("Cannot retrieve dm-crypt device status\n");
1080 goto errout;
1081 }
1082 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1083 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1084
Ken Sumralldb5e0262013-02-05 17:39:48 -08001085 extra_params = "";
1086 if (! get_dm_crypt_version(fd, name, version)) {
1087 /* Support for allow_discards was added in version 1.11.0 */
1088 if ((version[0] >= 2) ||
1089 ((version[0] == 1) && (version[1] >= 11))) {
1090 extra_params = "1 allow_discards";
1091 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1092 }
Ken Sumralle919efe2012-09-29 17:07:41 -07001093 }
1094
Ken Sumralldb5e0262013-02-05 17:39:48 -08001095 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1096 fd, extra_params);
1097 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001098 SLOGE("Cannot load dm-crypt mapping table.\n");
1099 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001100 } else if (load_count > 1) {
1101 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001102 }
1103
1104 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -08001105 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001106
1107 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1108 SLOGE("Cannot resume the dm-crypt device\n");
1109 goto errout;
1110 }
1111
1112 /* We made it here with no errors. Woot! */
1113 retval = 0;
1114
1115errout:
1116 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1117
1118 return retval;
1119}
1120
Ken Sumrall29d8da82011-05-18 17:20:07 -07001121static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001122{
1123 int fd;
1124 char buffer[DM_CRYPT_BUF_SIZE];
1125 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001126 int retval = -1;
1127
1128 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1129 SLOGE("Cannot open device-mapper\n");
1130 goto errout;
1131 }
1132
1133 io = (struct dm_ioctl *) buffer;
1134
1135 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1136 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1137 SLOGE("Cannot remove dm-crypt device\n");
1138 goto errout;
1139 }
1140
1141 /* We made it here with no errors. Woot! */
1142 retval = 0;
1143
1144errout:
1145 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1146
1147 return retval;
1148
1149}
1150
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001151static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001152 unsigned char *ikey, void *params UNUSED)
1153{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001154 SLOGI("Using pbkdf2 for cryptfs KDF");
1155
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001156 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001157 unsigned int keysize;
1158 char* master_key = (char*)convert_hex_ascii_to_key(passwd, &keysize);
1159 if (!master_key) return -1;
1160 PKCS5_PBKDF2_HMAC_SHA1(master_key, keysize, salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001161 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001162
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001163 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001164 free (master_key);
1165 return 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001166}
1167
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001168static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001169 unsigned char *ikey, void *params)
1170{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001171 SLOGI("Using scrypt for cryptfs KDF");
1172
Kenny Rootc4c70f12013-06-14 12:11:38 -07001173 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1174
1175 int N = 1 << ftr->N_factor;
1176 int r = 1 << ftr->r_factor;
1177 int p = 1 << ftr->p_factor;
1178
1179 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001180 unsigned int keysize;
1181 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &keysize);
1182 if (!master_key) return -1;
1183 crypto_scrypt(master_key, keysize, salt, SALT_LEN, N, r, p, ikey,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001184 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001185
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001186 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001187 free (master_key);
1188 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001189}
1190
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001191static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1192 unsigned char *ikey, void *params)
1193{
1194 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1195
1196 int rc;
1197 unsigned int key_size;
1198 size_t signature_size;
1199 unsigned char* signature;
1200 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1201
1202 int N = 1 << ftr->N_factor;
1203 int r = 1 << ftr->r_factor;
1204 int p = 1 << ftr->p_factor;
1205
1206 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &key_size);
1207 if (!master_key) {
1208 SLOGE("Failed to convert passwd from hex");
1209 return -1;
1210 }
1211
1212 rc = crypto_scrypt(master_key, key_size, salt, SALT_LEN,
1213 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1214 memset(master_key, 0, key_size);
1215 free(master_key);
1216
1217 if (rc) {
1218 SLOGE("scrypt failed");
1219 return -1;
1220 }
1221
Shawn Willdene17a9c42014-09-08 13:04:08 -06001222 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1223 &signature, &signature_size)) {
1224 SLOGE("Signing failed");
1225 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001226 }
1227
1228 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1229 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1230 free(signature);
1231
1232 if (rc) {
1233 SLOGE("scrypt failed");
1234 return -1;
1235 }
1236
1237 return 0;
1238}
1239
1240static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1241 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001242 unsigned char *encrypted_master_key,
1243 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001244{
1245 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1246 EVP_CIPHER_CTX e_ctx;
1247 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001248 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001249
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001250 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001251 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001252
1253 switch (crypt_ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001254 case KDF_SCRYPT_KEYMASTER_UNPADDED:
1255 case KDF_SCRYPT_KEYMASTER_BADLY_PADDED:
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001256 case KDF_SCRYPT_KEYMASTER:
1257 if (keymaster_create_key(crypt_ftr)) {
1258 SLOGE("keymaster_create_key failed");
1259 return -1;
1260 }
1261
1262 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1263 SLOGE("scrypt failed");
1264 return -1;
1265 }
1266 break;
1267
1268 case KDF_SCRYPT:
1269 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1270 SLOGE("scrypt failed");
1271 return -1;
1272 }
1273 break;
1274
1275 default:
1276 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001277 return -1;
1278 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001279
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001280 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001281 EVP_CIPHER_CTX_init(&e_ctx);
1282 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001283 SLOGE("EVP_EncryptInit failed\n");
1284 return -1;
1285 }
1286 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001287
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001288 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001289 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
1290 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001291 SLOGE("EVP_EncryptUpdate failed\n");
1292 return -1;
1293 }
Adam Langley889c4f12014-09-03 14:23:13 -07001294 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001295 SLOGE("EVP_EncryptFinal failed\n");
1296 return -1;
1297 }
1298
1299 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1300 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1301 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001302 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001303
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001304 /* Store the scrypt of the intermediate key, so we can validate if it's a
1305 password error or mount error when things go wrong.
1306 Note there's no need to check for errors, since if this is incorrect, we
1307 simply won't wipe userdata, which is the correct default behavior
1308 */
1309 int N = 1 << crypt_ftr->N_factor;
1310 int r = 1 << crypt_ftr->r_factor;
1311 int p = 1 << crypt_ftr->p_factor;
1312
1313 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1314 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1315 crypt_ftr->scrypted_intermediate_key,
1316 sizeof(crypt_ftr->scrypted_intermediate_key));
1317
1318 if (rc) {
1319 SLOGE("encrypt_master_key: crypto_scrypt failed");
1320 }
1321
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001322 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001323}
1324
JP Abgrall7bdfa522013-11-15 13:42:56 -08001325static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001326 unsigned char *encrypted_master_key,
1327 unsigned char *decrypted_master_key,
1328 kdf_func kdf, void *kdf_params,
1329 unsigned char** intermediate_key,
1330 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001331{
1332 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 -08001333 EVP_CIPHER_CTX d_ctx;
1334 int decrypted_len, final_len;
1335
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001336 /* Turn the password into an intermediate key and IV that can decrypt the
1337 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001338 if (kdf(passwd, salt, ikey, kdf_params)) {
1339 SLOGE("kdf failed");
1340 return -1;
1341 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001342
1343 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001344 EVP_CIPHER_CTX_init(&d_ctx);
1345 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001346 return -1;
1347 }
1348 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1349 /* Decrypt the master key */
1350 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1351 encrypted_master_key, KEY_LEN_BYTES)) {
1352 return -1;
1353 }
Adam Langley889c4f12014-09-03 14:23:13 -07001354 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001355 return -1;
1356 }
1357
1358 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1359 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001360 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001361
1362 /* Copy intermediate key if needed by params */
1363 if (intermediate_key && intermediate_key_size) {
1364 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1365 if (intermediate_key) {
1366 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1367 *intermediate_key_size = KEY_LEN_BYTES;
1368 }
1369 }
1370
1371 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001372}
1373
Kenny Rootc4c70f12013-06-14 12:11:38 -07001374static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001375{
Shawn Willdene17a9c42014-09-08 13:04:08 -06001376 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER_UNPADDED ||
1377 ftr->kdf_type == KDF_SCRYPT_KEYMASTER_BADLY_PADDED ||
1378 ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001379 *kdf = scrypt_keymaster;
1380 *kdf_params = ftr;
1381 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001382 *kdf = scrypt;
1383 *kdf_params = ftr;
1384 } else {
1385 *kdf = pbkdf2;
1386 *kdf_params = NULL;
1387 }
1388}
1389
JP Abgrall7bdfa522013-11-15 13:42:56 -08001390static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001391 struct crypt_mnt_ftr *crypt_ftr,
1392 unsigned char** intermediate_key,
1393 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001394{
1395 kdf_func kdf;
1396 void *kdf_params;
1397 int ret;
1398
1399 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001400 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1401 decrypted_master_key, kdf, kdf_params,
1402 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001403 if (ret != 0) {
1404 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001405 }
1406
1407 return ret;
1408}
1409
1410static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1411 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001412 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001413 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001414
1415 /* Get some random bits for a key */
1416 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001417 read(fd, key_buf, sizeof(key_buf));
1418 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001419 close(fd);
1420
1421 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001422 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001423}
1424
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001425static int wait_and_unmount(char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001426{
Greg Hackmann955653e2014-09-24 14:55:20 -07001427 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001428#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001429
1430 /* Now umount the tmpfs filesystem */
1431 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001432 if (umount(mountpoint) == 0) {
1433 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001434 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001435
1436 if (errno == EINVAL) {
1437 /* EINVAL is returned if the directory is not a mountpoint,
1438 * i.e. there is no filesystem mounted there. So just get out.
1439 */
1440 break;
1441 }
1442
1443 err = errno;
1444
1445 /* If allowed, be increasingly aggressive before the last two retries */
1446 if (kill) {
1447 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1448 SLOGW("sending SIGHUP to processes with open files\n");
1449 vold_killProcessesWithOpenFiles(mountpoint, 1);
1450 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1451 SLOGW("sending SIGKILL to processes with open files\n");
1452 vold_killProcessesWithOpenFiles(mountpoint, 2);
1453 }
1454 }
1455
1456 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001457 }
1458
1459 if (i < WAIT_UNMOUNT_COUNT) {
1460 SLOGD("unmounting %s succeeded\n", mountpoint);
1461 rc = 0;
1462 } else {
jessica_yu3f14fe42014-09-22 15:57:40 +08001463 vold_killProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001464 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001465 rc = -1;
1466 }
1467
1468 return rc;
1469}
1470
Ken Sumrallc5872692013-05-14 15:26:31 -07001471#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001472static int prep_data_fs(void)
1473{
1474 int i;
1475
1476 /* Do the prep of the /data filesystem */
1477 property_set("vold.post_fs_data_done", "0");
1478 property_set("vold.decrypt", "trigger_post_fs_data");
1479 SLOGD("Just triggered post_fs_data\n");
1480
Ken Sumrallc5872692013-05-14 15:26:31 -07001481 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001482 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001483 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001484
1485 property_get("vold.post_fs_data_done", p, "0");
1486 if (*p == '1') {
1487 break;
1488 } else {
1489 usleep(250000);
1490 }
1491 }
1492 if (i == DATA_PREP_TIMEOUT) {
1493 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001494 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001495 return -1;
1496 } else {
1497 SLOGD("post_fs_data done\n");
1498 return 0;
1499 }
1500}
1501
Paul Lawrence74f29f12014-08-28 15:54:10 -07001502static void cryptfs_set_corrupt()
1503{
1504 // Mark the footer as bad
1505 struct crypt_mnt_ftr crypt_ftr;
1506 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1507 SLOGE("Failed to get crypto footer - panic");
1508 return;
1509 }
1510
1511 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1512 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1513 SLOGE("Failed to set crypto footer - panic");
1514 return;
1515 }
1516}
1517
1518static void cryptfs_trigger_restart_min_framework()
1519{
1520 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1521 SLOGE("Failed to mount tmpfs on data - panic");
1522 return;
1523 }
1524
1525 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1526 SLOGE("Failed to trigger post fs data - panic");
1527 return;
1528 }
1529
1530 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1531 SLOGE("Failed to trigger restart min framework - panic");
1532 return;
1533 }
1534}
1535
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001536/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001537static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001538{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001539 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001540 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001541 static int restart_successful = 0;
1542
1543 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001544 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001545 SLOGE("Encrypted filesystem not validated, aborting");
1546 return -1;
1547 }
1548
1549 if (restart_successful) {
1550 SLOGE("System already restarted with encrypted disk, aborting");
1551 return -1;
1552 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001553
Paul Lawrencef4faa572014-01-29 13:31:03 -08001554 if (restart_main) {
1555 /* Here is where we shut down the framework. The init scripts
1556 * start all services in one of three classes: core, main or late_start.
1557 * On boot, we start core and main. Now, we stop main, but not core,
1558 * as core includes vold and a few other really important things that
1559 * we need to keep running. Once main has stopped, we should be able
1560 * to umount the tmpfs /data, then mount the encrypted /data.
1561 * We then restart the class main, and also the class late_start.
1562 * At the moment, I've only put a few things in late_start that I know
1563 * are not needed to bring up the framework, and that also cause problems
1564 * with unmounting the tmpfs /data, but I hope to add add more services
1565 * to the late_start class as we optimize this to decrease the delay
1566 * till the user is asked for the password to the filesystem.
1567 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001568
Paul Lawrencef4faa572014-01-29 13:31:03 -08001569 /* The init files are setup to stop the class main when vold.decrypt is
1570 * set to trigger_reset_main.
1571 */
1572 property_set("vold.decrypt", "trigger_reset_main");
1573 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001574
Paul Lawrencef4faa572014-01-29 13:31:03 -08001575 /* Ugh, shutting down the framework is not synchronous, so until it
1576 * can be fixed, this horrible hack will wait a moment for it all to
1577 * shut down before proceeding. Without it, some devices cannot
1578 * restart the graphics services.
1579 */
1580 sleep(2);
1581 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001582
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001583 /* Now that the framework is shutdown, we should be able to umount()
1584 * the tmpfs filesystem, and mount the real one.
1585 */
1586
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001587 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1588 if (strlen(crypto_blkdev) == 0) {
1589 SLOGE("fs_crypto_blkdev not set\n");
1590 return -1;
1591 }
1592
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001593 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001594 /* If ro.crypto.readonly is set to 1, mount the decrypted
1595 * filesystem readonly. This is used when /data is mounted by
1596 * recovery mode.
1597 */
1598 char ro_prop[PROPERTY_VALUE_MAX];
1599 property_get("ro.crypto.readonly", ro_prop, "");
1600 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1601 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1602 rec->flags |= MS_RDONLY;
1603 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001604
Ken Sumralle5032c42012-04-01 23:58:44 -07001605 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001606 int retries = RETRY_MOUNT_ATTEMPTS;
1607 int mount_rc;
1608 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1609 crypto_blkdev, 0))
1610 != 0) {
1611 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1612 /* TODO: invoke something similar to
1613 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1614 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1615 SLOGI("Failed to mount %s because it is busy - waiting",
1616 crypto_blkdev);
1617 if (--retries) {
1618 sleep(RETRY_MOUNT_DELAY_SECONDS);
1619 } else {
1620 /* Let's hope that a reboot clears away whatever is keeping
1621 the mount busy */
1622 cryptfs_reboot(reboot);
1623 }
1624 } else {
1625 SLOGE("Failed to mount decrypted data");
1626 cryptfs_set_corrupt();
1627 cryptfs_trigger_restart_min_framework();
1628 SLOGI("Started framework to offer wipe");
1629 return -1;
1630 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001631 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001632
Ken Sumralle5032c42012-04-01 23:58:44 -07001633 property_set("vold.decrypt", "trigger_load_persist_props");
1634 /* Create necessary paths on /data */
1635 if (prep_data_fs()) {
1636 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001637 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001638
1639 /* startup service classes main and late_start */
1640 property_set("vold.decrypt", "trigger_restart_framework");
1641 SLOGD("Just triggered restart_framework\n");
1642
1643 /* Give it a few moments to get started */
1644 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001645 }
1646
Ken Sumrall0cc16632011-01-18 20:32:26 -08001647 if (rc == 0) {
1648 restart_successful = 1;
1649 }
1650
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001651 return rc;
1652}
1653
Paul Lawrencef4faa572014-01-29 13:31:03 -08001654int cryptfs_restart(void)
1655{
1656 /* Call internal implementation forcing a restart of main service group */
1657 return cryptfs_restart_internal(1);
1658}
1659
Mark Salyzyn3e971272014-01-21 13:27:04 -08001660static int do_crypto_complete(char *mount_point UNUSED)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001661{
1662 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001663 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001664 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001665
1666 property_get("ro.crypto.state", encrypted_state, "");
1667 if (strcmp(encrypted_state, "encrypted") ) {
1668 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001669 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001670 }
1671
Ken Sumrall160b4d62013-04-22 12:15:39 -07001672 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001673 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001674
Ken Sumralle1a45852011-12-14 21:24:27 -08001675 /*
1676 * Only report this error if key_loc is a file and it exists.
1677 * If the device was never encrypted, and /data is not mountable for
1678 * some reason, returning 1 should prevent the UI from presenting the
1679 * a "enter password" screen, or worse, a "press button to wipe the
1680 * device" screen.
1681 */
1682 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1683 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001684 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001685 } else {
1686 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001687 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001688 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001689 }
1690
Paul Lawrence74f29f12014-08-28 15:54:10 -07001691 // Test for possible error flags
1692 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1693 SLOGE("Encryption process is partway completed\n");
1694 return CRYPTO_COMPLETE_PARTIAL;
1695 }
1696
1697 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1698 SLOGE("Encryption process was interrupted but cannot continue\n");
1699 return CRYPTO_COMPLETE_INCONSISTENT;
1700 }
1701
1702 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1703 SLOGE("Encryption is successful but data is corrupt\n");
1704 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001705 }
1706
1707 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001708 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001709}
1710
Paul Lawrencef4faa572014-01-29 13:31:03 -08001711static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1712 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001713{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001714 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001715 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001716 char crypto_blkdev[MAXPATHLEN];
1717 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001718 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001719 unsigned int orig_failed_decrypt_count;
1720 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001721 int use_keymaster = 0;
1722 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001723 unsigned char* intermediate_key = 0;
1724 size_t intermediate_key_size = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001725
Paul Lawrencef4faa572014-01-29 13:31:03 -08001726 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1727 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001728
Paul Lawrencef4faa572014-01-29 13:31:03 -08001729 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001730 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1731 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001732 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001733 rc = -1;
1734 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001735 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001736 }
1737
Paul Lawrencef4faa572014-01-29 13:31:03 -08001738 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1739
Paul Lawrence74f29f12014-08-28 15:54:10 -07001740 // Create crypto block device - all (non fatal) code paths
1741 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001742 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1743 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001744 SLOGE("Error creating decrypted block device\n");
1745 rc = -1;
1746 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001747 }
1748
Paul Lawrence74f29f12014-08-28 15:54:10 -07001749 /* Work out if the problem is the password or the data */
1750 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1751 scrypted_intermediate_key)];
1752 int N = 1 << crypt_ftr->N_factor;
1753 int r = 1 << crypt_ftr->r_factor;
1754 int p = 1 << crypt_ftr->p_factor;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001755
Paul Lawrence74f29f12014-08-28 15:54:10 -07001756 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1757 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1758 N, r, p, scrypted_intermediate_key,
1759 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001760
Paul Lawrence74f29f12014-08-28 15:54:10 -07001761 // Does the key match the crypto footer?
1762 if (rc == 0 && memcmp(scrypted_intermediate_key,
1763 crypt_ftr->scrypted_intermediate_key,
1764 sizeof(scrypted_intermediate_key)) == 0) {
1765 SLOGI("Password matches");
1766 rc = 0;
1767 } else {
1768 /* Try mounting the file system anyway, just in case the problem's with
1769 * the footer, not the key. */
1770 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1771 mkdir(tmp_mount_point, 0755);
1772 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1773 SLOGE("Error temp mounting decrypted block device\n");
1774 delete_crypto_blk_dev(label);
1775
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001776 rc = ++crypt_ftr->failed_decrypt_count;
1777 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001778 } else {
1779 /* Success! */
1780 SLOGI("Password did not match but decrypted drive mounted - continue");
1781 umount(tmp_mount_point);
1782 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001783 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001784 }
1785
1786 if (rc == 0) {
1787 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001788 if (orig_failed_decrypt_count != 0) {
1789 put_crypt_ftr_and_key(crypt_ftr);
1790 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001791
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001792 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001793 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001794 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001795
1796 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001797 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001798 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001799 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001800 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001801 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001802 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001803
Paul Lawrence74f29f12014-08-28 15:54:10 -07001804 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001805 use_keymaster = keymaster_check_compatibility();
1806 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001807 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001808 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1809 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1810 upgrade = 1;
1811 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001812 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001813 upgrade = 1;
1814 }
1815
1816 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001817 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1818 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001819 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001820 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001821 }
1822 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001823
1824 // Do not fail even if upgrade failed - machine is bootable
1825 // Note that if this code is ever hit, there is a *serious* problem
1826 // since KDFs should never fail. You *must* fix the kdf before
1827 // proceeding!
1828 if (rc) {
1829 SLOGW("Upgrade failed with error %d,"
1830 " but continuing with previous state",
1831 rc);
1832 rc = 0;
1833 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001834 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001835 }
1836
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001837 errout:
1838 if (intermediate_key) {
1839 memset(intermediate_key, 0, intermediate_key_size);
1840 free(intermediate_key);
1841 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001842 return rc;
1843}
1844
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001845/* Called by vold when it wants to undo the crypto mapping of a volume it
1846 * manages. This is usually in response to a factory reset, when we want
1847 * to undo the crypto mapping so the volume is formatted in the clear.
1848 */
1849int cryptfs_revert_volume(const char *label)
1850{
1851 return delete_crypto_blk_dev((char *)label);
1852}
1853
Ken Sumrall29d8da82011-05-18 17:20:07 -07001854/*
1855 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1856 * Setup a dm-crypt mapping, use the saved master key from
1857 * setting up the /data mapping, and return the new device path.
1858 */
1859int cryptfs_setup_volume(const char *label, int major, int minor,
1860 char *crypto_sys_path, unsigned int max_path,
1861 int *new_major, int *new_minor)
1862{
1863 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1864 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001865 struct stat statbuf;
Tim Murray8439dc92014-12-15 11:56:11 -08001866 unsigned int nr_sec;
1867 int fd;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001868
1869 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1870
Ken Sumrall160b4d62013-04-22 12:15:39 -07001871 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001872
1873 /* Update the fs_size field to be the size of the volume */
1874 fd = open(real_blkdev, O_RDONLY);
1875 nr_sec = get_blkdev_size(fd);
1876 close(fd);
1877 if (nr_sec == 0) {
1878 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1879 return -1;
1880 }
1881
1882 sd_crypt_ftr.fs_size = nr_sec;
1883 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1884 crypto_blkdev, label);
1885
1886 stat(crypto_blkdev, &statbuf);
1887 *new_major = MAJOR(statbuf.st_rdev);
1888 *new_minor = MINOR(statbuf.st_rdev);
1889
1890 /* Create path to sys entry for this block device */
1891 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1892
1893 return 0;
1894}
1895
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001896int cryptfs_crypto_complete(void)
1897{
1898 return do_crypto_complete("/data");
1899}
1900
Paul Lawrencef4faa572014-01-29 13:31:03 -08001901int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1902{
1903 char encrypted_state[PROPERTY_VALUE_MAX];
1904 property_get("ro.crypto.state", encrypted_state, "");
1905 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1906 SLOGE("encrypted fs already validated or not running with encryption,"
1907 " aborting");
1908 return -1;
1909 }
1910
1911 if (get_crypt_ftr_and_key(crypt_ftr)) {
1912 SLOGE("Error getting crypt footer and key");
1913 return -1;
1914 }
1915
1916 return 0;
1917}
1918
Paul Lawrencefc615042014-10-04 15:32:29 -07001919/*
1920 * TODO - transition patterns to new format in calling code
1921 * and remove this vile hack, and the use of hex in
1922 * the password passing code.
1923 *
1924 * Patterns are passed in zero based (i.e. the top left dot
1925 * is represented by zero, the top middle one etc), but we want
1926 * to store them '1' based.
1927 * This is to allow us to migrate the calling code to use this
1928 * convention. It also solves a nasty problem whereby scrypt ignores
1929 * trailing zeros, so patterns ending at the top left could be
1930 * truncated, and similarly, you could add the top left to any
1931 * pattern and still match.
1932 * adjust_passwd is a hack function that returns the alternate representation
1933 * if the password appears to be a pattern (hex numbers all less than 09)
1934 * If it succeeds we need to try both, and in particular try the alternate
1935 * first. If the original matches, then we need to update the footer
1936 * with the alternate.
1937 * All code that accepts passwords must adjust them first. Since
1938 * cryptfs_check_passwd is always the first function called after a migration
1939 * (and indeed on any boot) we only need to do the double try in this
1940 * function.
1941 */
1942char* adjust_passwd(const char* passwd)
1943{
1944 size_t index, length;
1945
1946 if (!passwd) {
1947 return 0;
1948 }
1949
1950 // Check even length. Hex encoded passwords are always
1951 // an even length, since each character encodes to two characters.
1952 length = strlen(passwd);
1953 if (length % 2) {
1954 SLOGW("Password not correctly hex encoded.");
1955 return 0;
1956 }
1957
1958 // Check password is old-style pattern - a collection of hex
1959 // encoded bytes less than 9 (00 through 08)
1960 for (index = 0; index < length; index +=2) {
1961 if (passwd[index] != '0'
1962 || passwd[index + 1] < '0' || passwd[index + 1] > '8') {
1963 return 0;
1964 }
1965 }
1966
1967 // Allocate room for adjusted passwd and null terminate
1968 char* adjusted = malloc(length + 1);
1969 adjusted[length] = 0;
1970
1971 // Add 0x31 ('1') to each character
1972 for (index = 0; index < length; index += 2) {
1973 // output is 31 through 39 so set first byte to three, second to src + 1
1974 adjusted[index] = '3';
1975 adjusted[index + 1] = passwd[index + 1] + 1;
1976 }
1977
1978 return adjusted;
1979}
1980
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001981int cryptfs_check_passwd(char *passwd)
1982{
Paul Lawrencef4faa572014-01-29 13:31:03 -08001983 struct crypt_mnt_ftr crypt_ftr;
1984 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001985
Paul Lawrencef4faa572014-01-29 13:31:03 -08001986 rc = check_unmounted_and_get_ftr(&crypt_ftr);
1987 if (rc)
1988 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001989
Paul Lawrencefc615042014-10-04 15:32:29 -07001990 char* adjusted_passwd = adjust_passwd(passwd);
1991 if (adjusted_passwd) {
1992 int failed_decrypt_count = crypt_ftr.failed_decrypt_count;
1993 rc = test_mount_encrypted_fs(&crypt_ftr, adjusted_passwd,
1994 DATA_MNT_POINT, "userdata");
1995
1996 // Maybe the original one still works?
1997 if (rc) {
1998 // Don't double count this failure
1999 crypt_ftr.failed_decrypt_count = failed_decrypt_count;
2000 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
2001 DATA_MNT_POINT, "userdata");
2002 if (!rc) {
2003 // cryptfs_changepw also adjusts so pass original
2004 // Note that adjust_passwd only recognises patterns
2005 // so we can safely use CRYPT_TYPE_PATTERN
2006 SLOGI("Updating pattern to new format");
2007 cryptfs_changepw(CRYPT_TYPE_PATTERN, passwd);
2008 }
2009 }
2010 free(adjusted_passwd);
2011 } else {
2012 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
2013 DATA_MNT_POINT, "userdata");
2014 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002015
2016 if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002017 cryptfs_clear_password();
2018 password = strdup(passwd);
2019 struct timespec now;
2020 clock_gettime(CLOCK_BOOTTIME, &now);
2021 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002022 }
2023
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002024 return rc;
2025}
2026
Ken Sumrall3ad90722011-10-04 20:38:29 -07002027int cryptfs_verify_passwd(char *passwd)
2028{
2029 struct crypt_mnt_ftr crypt_ftr;
2030 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002031 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002032 char encrypted_state[PROPERTY_VALUE_MAX];
2033 int rc;
2034
2035 property_get("ro.crypto.state", encrypted_state, "");
2036 if (strcmp(encrypted_state, "encrypted") ) {
2037 SLOGE("device not encrypted, aborting");
2038 return -2;
2039 }
2040
2041 if (!master_key_saved) {
2042 SLOGE("encrypted fs not yet mounted, aborting");
2043 return -1;
2044 }
2045
2046 if (!saved_mount_point) {
2047 SLOGE("encrypted fs failed to save mount point, aborting");
2048 return -1;
2049 }
2050
Ken Sumrall160b4d62013-04-22 12:15:39 -07002051 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002052 SLOGE("Error getting crypt footer and key\n");
2053 return -1;
2054 }
2055
2056 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2057 /* If the device has no password, then just say the password is valid */
2058 rc = 0;
2059 } else {
Paul Lawrencefc615042014-10-04 15:32:29 -07002060 char* adjusted_passwd = adjust_passwd(passwd);
2061 if (adjusted_passwd) {
2062 passwd = adjusted_passwd;
2063 }
2064
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002065 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002066 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2067 /* They match, the password is correct */
2068 rc = 0;
2069 } else {
2070 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2071 sleep(1);
2072 rc = 1;
2073 }
Paul Lawrencefc615042014-10-04 15:32:29 -07002074
2075 free(adjusted_passwd);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002076 }
2077
2078 return rc;
2079}
2080
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002081/* Initialize a crypt_mnt_ftr structure. The keysize is
2082 * defaulted to 16 bytes, and the filesystem size to 0.
2083 * Presumably, at a minimum, the caller will update the
2084 * filesystem size and crypto_type_name after calling this function.
2085 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002086static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002087{
Ken Sumrall160b4d62013-04-22 12:15:39 -07002088 off64_t off;
2089
2090 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002091 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002092 ftr->major_version = CURRENT_MAJOR_VERSION;
2093 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002094 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06002095 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002096
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002097 switch (keymaster_check_compatibility()) {
2098 case 1:
2099 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2100 break;
2101
2102 case 0:
2103 ftr->kdf_type = KDF_SCRYPT;
2104 break;
2105
2106 default:
2107 SLOGE("keymaster_check_compatibility failed");
2108 return -1;
2109 }
2110
Kenny Rootc4c70f12013-06-14 12:11:38 -07002111 get_device_scrypt_params(ftr);
2112
Ken Sumrall160b4d62013-04-22 12:15:39 -07002113 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2114 if (get_crypt_ftr_info(NULL, &off) == 0) {
2115 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
2116 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
2117 ftr->persist_data_size;
2118 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002119
2120 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002121}
2122
Ken Sumrall29d8da82011-05-18 17:20:07 -07002123static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002124{
Ken Sumralle550f782013-08-20 13:48:23 -07002125 const char *args[10];
2126 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
2127 int num_args;
2128 int status;
2129 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002130 int rc = -1;
2131
Ken Sumrall29d8da82011-05-18 17:20:07 -07002132 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07002133 args[0] = "/system/bin/make_ext4fs";
2134 args[1] = "-a";
2135 args[2] = "/data";
2136 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07002137 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07002138 args[4] = size_str;
2139 args[5] = crypto_blkdev;
2140 num_args = 6;
2141 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
2142 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07002143 } else if (type == F2FS_FS) {
2144 args[0] = "/system/bin/mkfs.f2fs";
2145 args[1] = "-t";
2146 args[2] = "-d1";
2147 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07002148 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07002149 args[4] = size_str;
2150 num_args = 5;
2151 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
2152 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002153 } else {
2154 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
2155 return -1;
2156 }
2157
Ken Sumralle550f782013-08-20 13:48:23 -07002158 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
2159
2160 if (tmp != 0) {
2161 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002162 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07002163 if (WIFEXITED(status)) {
2164 if (WEXITSTATUS(status)) {
2165 SLOGE("Error creating filesystem on %s, exit status %d ",
2166 crypto_blkdev, WEXITSTATUS(status));
2167 } else {
2168 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
2169 rc = 0;
2170 }
2171 } else {
2172 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
2173 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002174 }
2175
2176 return rc;
2177}
2178
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002179#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08002180#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
2181#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002182
2183/* aligned 32K writes tends to make flash happy.
2184 * SD card association recommends it.
2185 */
2186#define BLOCKS_AT_A_TIME 8
2187
2188struct encryptGroupsData
2189{
2190 int realfd;
2191 int cryptofd;
2192 off64_t numblocks;
2193 off64_t one_pct, cur_pct, new_pct;
2194 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002195 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002196 char* real_blkdev, * crypto_blkdev;
2197 int count;
2198 off64_t offset;
2199 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08002200 off64_t last_written_sector;
2201 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002202 time_t time_started;
2203 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002204};
2205
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002206static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002207{
2208 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002209
2210 if (is_used) {
2211 data->used_blocks_already_done++;
2212 }
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002213 if (data->tot_used_blocks) {
2214 data->new_pct = data->used_blocks_already_done / data->one_pct;
2215 } else {
2216 data->new_pct = data->blocks_already_done / data->one_pct;
2217 }
2218
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002219 if (data->new_pct > data->cur_pct) {
2220 char buf[8];
2221 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07002222 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002223 property_set("vold.encrypt_progress", buf);
2224 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002225
2226 if (data->cur_pct >= 5) {
Paul Lawrence9c58a872014-09-30 09:12:51 -07002227 struct timespec time_now;
2228 if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
2229 SLOGW("Error getting time");
2230 } else {
2231 double elapsed_time = difftime(time_now.tv_sec, data->time_started);
2232 off64_t remaining_blocks = data->tot_used_blocks
2233 - data->used_blocks_already_done;
2234 int remaining_time = (int)(elapsed_time * remaining_blocks
2235 / data->used_blocks_already_done);
Paul Lawrence71577502014-08-13 14:55:55 -07002236
Paul Lawrence9c58a872014-09-30 09:12:51 -07002237 // Change time only if not yet set, lower, or a lot higher for
2238 // best user experience
2239 if (data->remaining_time == -1
2240 || remaining_time < data->remaining_time
2241 || remaining_time > data->remaining_time + 60) {
2242 char buf[8];
2243 snprintf(buf, sizeof(buf), "%d", remaining_time);
2244 property_set("vold.encrypt_time_remaining", buf);
2245 data->remaining_time = remaining_time;
2246 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002247 }
2248 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002249}
2250
Paul Lawrence3846be12014-09-22 11:33:54 -07002251static void log_progress(struct encryptGroupsData const* data, bool completed)
2252{
2253 // Precondition - if completed data = 0 else data != 0
2254
2255 // Track progress so we can skip logging blocks
2256 static off64_t offset = -1;
2257
2258 // Need to close existing 'Encrypting from' log?
2259 if (completed || (offset != -1 && data->offset != offset)) {
2260 SLOGI("Encrypted to sector %" PRId64,
2261 offset / info.block_size * CRYPT_SECTOR_SIZE);
2262 offset = -1;
2263 }
2264
2265 // Need to start new 'Encrypting from' log?
2266 if (!completed && offset != data->offset) {
2267 SLOGI("Encrypting from sector %" PRId64,
2268 data->offset / info.block_size * CRYPT_SECTOR_SIZE);
2269 }
2270
2271 // Update offset
2272 if (!completed) {
2273 offset = data->offset + (off64_t)data->count * info.block_size;
2274 }
2275}
2276
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002277static int flush_outstanding_data(struct encryptGroupsData* data)
2278{
2279 if (data->count == 0) {
2280 return 0;
2281 }
2282
Elliott Hughes231bdba2014-06-25 18:36:19 -07002283 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002284
2285 if (pread64(data->realfd, data->buffer,
2286 info.block_size * data->count, data->offset)
2287 <= 0) {
2288 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2289 data->real_blkdev);
2290 return -1;
2291 }
2292
2293 if (pwrite64(data->cryptofd, data->buffer,
2294 info.block_size * data->count, data->offset)
2295 <= 0) {
2296 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2297 data->crypto_blkdev);
2298 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002299 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002300 log_progress(data, false);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002301 }
2302
2303 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002304 data->last_written_sector = (data->offset + data->count)
2305 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002306 return 0;
2307}
2308
2309static int encrypt_groups(struct encryptGroupsData* data)
2310{
2311 unsigned int i;
2312 u8 *block_bitmap = 0;
2313 unsigned int block;
2314 off64_t ret;
2315 int rc = -1;
2316
2317 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
2318 if (!data->buffer) {
2319 SLOGE("Failed to allocate crypto buffer");
2320 goto errout;
2321 }
2322
2323 block_bitmap = malloc(info.block_size);
2324 if (!block_bitmap) {
2325 SLOGE("failed to allocate block bitmap");
2326 goto errout;
2327 }
2328
2329 for (i = 0; i < aux_info.groups; ++i) {
2330 SLOGI("Encrypting group %d", i);
2331
2332 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2333 u32 block_count = min(info.blocks_per_group,
2334 aux_info.len_blocks - first_block);
2335
2336 off64_t offset = (u64)info.block_size
2337 * aux_info.bg_desc[i].bg_block_bitmap;
2338
2339 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2340 if (ret != (int)info.block_size) {
2341 SLOGE("failed to read all of block group bitmap %d", i);
2342 goto errout;
2343 }
2344
2345 offset = (u64)info.block_size * first_block;
2346
2347 data->count = 0;
2348
2349 for (block = 0; block < block_count; block++) {
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002350 int used = bitmap_get_bit(block_bitmap, block);
2351 update_progress(data, used);
2352 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002353 if (data->count == 0) {
2354 data->offset = offset;
2355 }
2356 data->count++;
2357 } else {
2358 if (flush_outstanding_data(data)) {
2359 goto errout;
2360 }
2361 }
2362
2363 offset += info.block_size;
2364
2365 /* Write data if we are aligned or buffer size reached */
2366 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2367 || data->count == BLOCKS_AT_A_TIME) {
2368 if (flush_outstanding_data(data)) {
2369 goto errout;
2370 }
2371 }
Paul Lawrence87999172014-02-20 12:21:31 -08002372
Paul Lawrence73d7a022014-06-09 14:10:09 -07002373 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002374 SLOGE("Stopping encryption due to low battery");
2375 rc = 0;
2376 goto errout;
2377 }
2378
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002379 }
2380 if (flush_outstanding_data(data)) {
2381 goto errout;
2382 }
2383 }
2384
Paul Lawrence87999172014-02-20 12:21:31 -08002385 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002386 rc = 0;
2387
2388errout:
Paul Lawrence3846be12014-09-22 11:33:54 -07002389 log_progress(0, true);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002390 free(data->buffer);
2391 free(block_bitmap);
2392 return rc;
2393}
2394
2395static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2396 char *real_blkdev,
2397 off64_t size,
2398 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002399 off64_t tot_size,
2400 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002401{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002402 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002403 struct encryptGroupsData data;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002404 int rc; // Can't initialize without causing warning -Wclobbered
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002405
Paul Lawrence87999172014-02-20 12:21:31 -08002406 if (previously_encrypted_upto > *size_already_done) {
2407 SLOGD("Not fast encrypting since resuming part way through");
2408 return -1;
2409 }
2410
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002411 memset(&data, 0, sizeof(data));
2412 data.real_blkdev = real_blkdev;
2413 data.crypto_blkdev = crypto_blkdev;
2414
2415 if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
JP Abgrall77768712014-10-10 15:52:11 -07002416 SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
2417 real_blkdev, errno, strerror(errno));
Paul Lawrence74f29f12014-08-28 15:54:10 -07002418 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002419 goto errout;
2420 }
2421
2422 if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002423 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
JP Abgrall77768712014-10-10 15:52:11 -07002424 crypto_blkdev, errno, strerror(errno));
JP Abgrall512f0d52014-10-10 18:43:41 -07002425 rc = ENABLE_INPLACE_ERR_DEV;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002426 goto errout;
2427 }
2428
2429 if (setjmp(setjmp_env)) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002430 SLOGE("Reading ext4 extent caused an exception\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002431 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002432 goto errout;
2433 }
2434
2435 if (read_ext(data.realfd, 0) != 0) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002436 SLOGE("Failed to read ext4 extent\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002437 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002438 goto errout;
2439 }
2440
2441 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2442 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2443 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2444
JP Abgrall512f0d52014-10-10 18:43:41 -07002445 SLOGI("Encrypting ext4 filesystem in place...");
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002446
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002447 data.tot_used_blocks = data.numblocks;
2448 for (i = 0; i < aux_info.groups; ++i) {
2449 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2450 }
2451
2452 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002453 data.cur_pct = 0;
Paul Lawrence9c58a872014-09-30 09:12:51 -07002454
2455 struct timespec time_started = {0};
2456 if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
2457 SLOGW("Error getting time at start");
2458 // Note - continue anyway - we'll run with 0
2459 }
2460 data.time_started = time_started.tv_sec;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002461 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002462
2463 rc = encrypt_groups(&data);
2464 if (rc) {
2465 SLOGE("Error encrypting groups");
2466 goto errout;
2467 }
2468
Paul Lawrence87999172014-02-20 12:21:31 -08002469 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002470 rc = 0;
2471
2472errout:
2473 close(data.realfd);
2474 close(data.cryptofd);
2475
2476 return rc;
2477}
2478
Paul Lawrence3846be12014-09-22 11:33:54 -07002479static void log_progress_f2fs(u64 block, bool completed)
2480{
2481 // Precondition - if completed data = 0 else data != 0
2482
2483 // Track progress so we can skip logging blocks
2484 static u64 last_block = (u64)-1;
2485
2486 // Need to close existing 'Encrypting from' log?
2487 if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
2488 SLOGI("Encrypted to block %" PRId64, last_block);
2489 last_block = -1;
2490 }
2491
2492 // Need to start new 'Encrypting from' log?
2493 if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
2494 SLOGI("Encrypting from block %" PRId64, block);
2495 }
2496
2497 // Update offset
2498 if (!completed) {
2499 last_block = block;
2500 }
2501}
2502
Daniel Rosenberge82df162014-08-15 22:19:23 +00002503static int encrypt_one_block_f2fs(u64 pos, void *data)
2504{
2505 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2506
2507 priv_dat->blocks_already_done = pos - 1;
2508 update_progress(priv_dat, 1);
2509
2510 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2511
2512 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002513 SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002514 return -1;
2515 }
2516
2517 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002518 SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002519 return -1;
2520 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002521 log_progress_f2fs(pos, false);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002522 }
2523
2524 return 0;
2525}
2526
2527static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2528 char *real_blkdev,
2529 off64_t size,
2530 off64_t *size_already_done,
2531 off64_t tot_size,
2532 off64_t previously_encrypted_upto)
2533{
Daniel Rosenberge82df162014-08-15 22:19:23 +00002534 struct encryptGroupsData data;
2535 struct f2fs_info *f2fs_info = NULL;
JP Abgrall512f0d52014-10-10 18:43:41 -07002536 int rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002537 if (previously_encrypted_upto > *size_already_done) {
2538 SLOGD("Not fast encrypting since resuming part way through");
JP Abgrall512f0d52014-10-10 18:43:41 -07002539 return ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002540 }
2541 memset(&data, 0, sizeof(data));
2542 data.real_blkdev = real_blkdev;
2543 data.crypto_blkdev = crypto_blkdev;
2544 data.realfd = -1;
2545 data.cryptofd = -1;
2546 if ( (data.realfd = open64(real_blkdev, O_RDWR)) < 0) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002547 SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
Daniel Rosenberge82df162014-08-15 22:19:23 +00002548 real_blkdev);
2549 goto errout;
2550 }
2551 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002552 SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
JP Abgrall77768712014-10-10 15:52:11 -07002553 crypto_blkdev, errno, strerror(errno));
JP Abgrall512f0d52014-10-10 18:43:41 -07002554 rc = ENABLE_INPLACE_ERR_DEV;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002555 goto errout;
2556 }
2557
2558 f2fs_info = generate_f2fs_info(data.realfd);
2559 if (!f2fs_info)
2560 goto errout;
2561
2562 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2563 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2564 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2565
2566 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2567
2568 data.one_pct = data.tot_used_blocks / 100;
2569 data.cur_pct = 0;
2570 data.time_started = time(NULL);
2571 data.remaining_time = -1;
2572
2573 data.buffer = malloc(f2fs_info->block_size);
2574 if (!data.buffer) {
2575 SLOGE("Failed to allocate crypto buffer");
2576 goto errout;
2577 }
2578
2579 data.count = 0;
2580
2581 /* Currently, this either runs to completion, or hits a nonrecoverable error */
2582 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2583
2584 if (rc) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002585 SLOGE("Error in running over f2fs blocks");
2586 rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002587 goto errout;
2588 }
2589
2590 *size_already_done += size;
2591 rc = 0;
2592
2593errout:
2594 if (rc)
2595 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2596
Paul Lawrence3846be12014-09-22 11:33:54 -07002597 log_progress_f2fs(0, true);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002598 free(f2fs_info);
2599 free(data.buffer);
2600 close(data.realfd);
2601 close(data.cryptofd);
2602
2603 return rc;
2604}
2605
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002606static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2607 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002608 off64_t tot_size,
2609 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002610{
2611 int realfd, cryptofd;
2612 char *buf[CRYPT_INPLACE_BUFSIZE];
JP Abgrall512f0d52014-10-10 18:43:41 -07002613 int rc = ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002614 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002615 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002616 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002617
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002618 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
2619 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
JP Abgrall512f0d52014-10-10 18:43:41 -07002620 return ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002621 }
2622
2623 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall77768712014-10-10 15:52:11 -07002624 SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
2625 crypto_blkdev, errno, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002626 close(realfd);
JP Abgrall512f0d52014-10-10 18:43:41 -07002627 return ENABLE_INPLACE_ERR_DEV;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002628 }
2629
2630 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2631 * The size passed in is the number of 512 byte sectors in the filesystem.
2632 * So compute the number of whole 4K blocks we should read/write,
2633 * and the remainder.
2634 */
2635 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2636 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002637 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2638 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002639
2640 SLOGE("Encrypting filesystem in place...");
2641
Paul Lawrence87999172014-02-20 12:21:31 -08002642 i = previously_encrypted_upto + 1 - *size_already_done;
2643
2644 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2645 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2646 goto errout;
2647 }
2648
2649 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2650 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2651 goto errout;
2652 }
2653
2654 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2655 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2656 SLOGE("Error reading initial sectors from real_blkdev %s for "
2657 "inplace encrypt\n", crypto_blkdev);
2658 goto errout;
2659 }
2660 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2661 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2662 "inplace encrypt\n", crypto_blkdev);
2663 goto errout;
2664 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002665 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002666 }
2667 }
2668
Ken Sumrall29d8da82011-05-18 17:20:07 -07002669 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002670 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002671 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002672 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002673 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002674 if (new_pct > cur_pct) {
2675 char buf[8];
2676
2677 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002678 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002679 property_set("vold.encrypt_progress", buf);
2680 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002681 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002682 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002683 goto errout;
2684 }
2685 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002686 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2687 goto errout;
2688 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002689 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002690 CRYPT_SECTORS_PER_BUFSIZE,
2691 i * CRYPT_SECTORS_PER_BUFSIZE);
2692 }
2693
Paul Lawrence73d7a022014-06-09 14:10:09 -07002694 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002695 SLOGE("Stopping encryption due to low battery");
2696 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2697 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002698 goto errout;
2699 }
2700 }
2701
2702 /* Do any remaining sectors */
2703 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002704 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2705 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002706 goto errout;
2707 }
Paul Lawrence87999172014-02-20 12:21:31 -08002708 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2709 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002710 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002711 } else {
2712 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002713 }
2714 }
2715
Ken Sumrall29d8da82011-05-18 17:20:07 -07002716 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002717 rc = 0;
2718
2719errout:
2720 close(realfd);
2721 close(cryptofd);
2722
2723 return rc;
2724}
2725
JP Abgrall512f0d52014-10-10 18:43:41 -07002726/* returns on of the ENABLE_INPLACE_* return codes */
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002727static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2728 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002729 off64_t tot_size,
2730 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002731{
JP Abgrall512f0d52014-10-10 18:43:41 -07002732 int rc_ext4, rc_f2fs, rc_full;
Paul Lawrence87999172014-02-20 12:21:31 -08002733 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002734 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002735 }
2736
2737 if (*size_already_done + size < previously_encrypted_upto) {
2738 *size_already_done += size;
2739 return 0;
2740 }
2741
Daniel Rosenberge82df162014-08-15 22:19:23 +00002742 /* TODO: identify filesystem type.
2743 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2744 * then we will drop down to cryptfs_enable_inplace_f2fs.
2745 * */
JP Abgrall512f0d52014-10-10 18:43:41 -07002746 if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002747 size, size_already_done,
JP Abgrall512f0d52014-10-10 18:43:41 -07002748 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002749 return 0;
2750 }
JP Abgrall512f0d52014-10-10 18:43:41 -07002751 SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002752
JP Abgrall512f0d52014-10-10 18:43:41 -07002753 if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002754 size, size_already_done,
JP Abgrall512f0d52014-10-10 18:43:41 -07002755 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002756 return 0;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002757 }
JP Abgrall512f0d52014-10-10 18:43:41 -07002758 SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002759
JP Abgrall512f0d52014-10-10 18:43:41 -07002760 rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002761 size, size_already_done, tot_size,
2762 previously_encrypted_upto);
JP Abgrall512f0d52014-10-10 18:43:41 -07002763 SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
2764
2765 /* Hack for b/17898962, the following is the symptom... */
2766 if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
2767 && rc_f2fs == ENABLE_INPLACE_ERR_DEV
2768 && rc_full == ENABLE_INPLACE_ERR_DEV) {
2769 return ENABLE_INPLACE_ERR_DEV;
2770 }
2771 return rc_full;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002772}
2773
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002774#define CRYPTO_ENABLE_WIPE 1
2775#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002776
2777#define FRAMEWORK_BOOT_WAIT 60
2778
Ken Sumrall29d8da82011-05-18 17:20:07 -07002779static inline int should_encrypt(struct volume_info *volume)
2780{
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002781 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
Ken Sumrall29d8da82011-05-18 17:20:07 -07002782 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
2783}
2784
Paul Lawrence87999172014-02-20 12:21:31 -08002785static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2786{
2787 int fd = open(filename, O_RDONLY);
2788 if (fd == -1) {
2789 SLOGE("Error opening file %s", filename);
2790 return -1;
2791 }
2792
2793 char block[CRYPT_INPLACE_BUFSIZE];
2794 memset(block, 0, sizeof(block));
2795 if (unix_read(fd, block, sizeof(block)) < 0) {
2796 SLOGE("Error reading file %s", filename);
2797 close(fd);
2798 return -1;
2799 }
2800
2801 close(fd);
2802
2803 SHA256_CTX c;
2804 SHA256_Init(&c);
2805 SHA256_Update(&c, block, sizeof(block));
2806 SHA256_Final(buf, &c);
2807
2808 return 0;
2809}
2810
JP Abgrall62c7af32014-06-16 13:01:23 -07002811static int get_fs_type(struct fstab_rec *rec)
2812{
2813 if (!strcmp(rec->fs_type, "ext4")) {
2814 return EXT4_FS;
2815 } else if (!strcmp(rec->fs_type, "f2fs")) {
2816 return F2FS_FS;
2817 } else {
2818 return -1;
2819 }
2820}
2821
Paul Lawrence87999172014-02-20 12:21:31 -08002822static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2823 char *crypto_blkdev, char *real_blkdev,
2824 int previously_encrypted_upto)
2825{
2826 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002827 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002828
Paul Lawrence73d7a022014-06-09 14:10:09 -07002829 if (!is_battery_ok_to_start()) {
2830 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002831 return 0;
2832 }
2833
2834 /* The size of the userdata partition, and add in the vold volumes below */
2835 tot_encryption_size = crypt_ftr->fs_size;
2836
2837 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002838 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2839 int fs_type = get_fs_type(rec);
2840 if (fs_type < 0) {
2841 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2842 return -1;
2843 }
2844 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002845 } else if (how == CRYPTO_ENABLE_INPLACE) {
2846 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2847 crypt_ftr->fs_size, &cur_encryption_done,
2848 tot_encryption_size,
2849 previously_encrypted_upto);
2850
JP Abgrall512f0d52014-10-10 18:43:41 -07002851 if (rc == ENABLE_INPLACE_ERR_DEV) {
2852 /* Hack for b/17898962 */
2853 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2854 cryptfs_reboot(reboot);
2855 }
2856
Paul Lawrence73d7a022014-06-09 14:10:09 -07002857 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002858 crypt_ftr->encrypted_upto = cur_encryption_done;
2859 }
2860
Paul Lawrence73d7a022014-06-09 14:10:09 -07002861 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002862 /* The inplace routine never actually sets the progress to 100% due
2863 * to the round down nature of integer division, so set it here */
2864 property_set("vold.encrypt_progress", "100");
2865 }
2866 } else {
2867 /* Shouldn't happen */
2868 SLOGE("cryptfs_enable: internal error, unknown option\n");
2869 rc = -1;
2870 }
2871
2872 return rc;
2873}
2874
Paul Lawrence13486032014-02-03 13:28:11 -08002875int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
2876 int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002877{
2878 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002879 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07002880 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002881 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Tim Murray8439dc92014-12-15 11:56:11 -08002882 int rc=-1, fd, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002883 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002884 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002885 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002886 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002887 char key_loc[PROPERTY_VALUE_MAX];
2888 char fuse_sdcard[PROPERTY_VALUE_MAX];
2889 char *sd_mnt_point;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002890 int num_vols;
2891 struct volume_info *vol_list = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002892 off64_t previously_encrypted_upto = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002893
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002894 if (!strcmp(howarg, "wipe")) {
2895 how = CRYPTO_ENABLE_WIPE;
2896 } else if (! strcmp(howarg, "inplace")) {
2897 how = CRYPTO_ENABLE_INPLACE;
2898 } else {
2899 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002900 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002901 }
2902
Paul Lawrence87999172014-02-20 12:21:31 -08002903 /* See if an encryption was underway and interrupted */
2904 if (how == CRYPTO_ENABLE_INPLACE
2905 && get_crypt_ftr_and_key(&crypt_ftr) == 0
2906 && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
2907 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2908 crypt_ftr.encrypted_upto = 0;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002909 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
2910
2911 /* At this point, we are in an inconsistent state. Until we successfully
2912 complete encryption, a reboot will leave us broken. So mark the
2913 encryption failed in case that happens.
2914 On successfully completing encryption, remove this flag */
2915 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2916
2917 put_crypt_ftr_and_key(&crypt_ftr);
Paul Lawrence87999172014-02-20 12:21:31 -08002918 }
2919
2920 property_get("ro.crypto.state", encrypted_state, "");
2921 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2922 SLOGE("Device is already running encrypted, aborting");
2923 goto error_unencrypted;
2924 }
2925
2926 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2927 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002928 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002929
Ken Sumrall3ed82362011-01-28 23:31:16 -08002930 /* Get the size of the real block device */
2931 fd = open(real_blkdev, O_RDONLY);
2932 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
2933 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2934 goto error_unencrypted;
2935 }
2936 close(fd);
2937
2938 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002939 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002940 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002941 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002942 if (fs_size_sec == 0)
2943 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2944
Paul Lawrence87999172014-02-20 12:21:31 -08002945 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002946
2947 if (fs_size_sec > max_fs_size_sec) {
2948 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2949 goto error_unencrypted;
2950 }
2951 }
2952
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002953 /* Get a wakelock as this may take a while, and we don't want the
2954 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2955 * wants to keep the screen on, it can grab a full wakelock.
2956 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002957 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002958 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2959
Jeff Sharkey7382f812012-08-23 14:08:59 -07002960 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07002961 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07002962 if (!sd_mnt_point) {
2963 sd_mnt_point = getenv("EXTERNAL_STORAGE");
2964 }
2965 if (!sd_mnt_point) {
2966 sd_mnt_point = "/mnt/sdcard";
2967 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07002968
Paul Lawrence87999172014-02-20 12:21:31 -08002969 /* TODO
2970 * Currently do not have test devices with multiple encryptable volumes.
2971 * When we acquire some, re-add support.
2972 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002973 num_vols=vold_getNumDirectVolumes();
2974 vol_list = malloc(sizeof(struct volume_info) * num_vols);
2975 vold_getDirectVolumeList(vol_list);
2976
2977 for (i=0; i<num_vols; i++) {
2978 if (should_encrypt(&vol_list[i])) {
Paul Lawrence87999172014-02-20 12:21:31 -08002979 SLOGE("Cannot encrypt if there are multiple encryptable volumes"
2980 "%s\n", vol_list[i].label);
2981 goto error_unencrypted;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002982 }
2983 }
2984
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002985 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002986 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002987 */
2988 property_set("vold.decrypt", "trigger_shutdown_framework");
2989 SLOGD("Just asked init to shut down class main\n");
2990
Ken Sumrall425524d2012-06-14 20:55:28 -07002991 if (vold_unmountAllAsecs()) {
2992 /* Just report the error. If any are left mounted,
2993 * umounting /data below will fail and handle the error.
2994 */
2995 SLOGE("Error unmounting internal asecs");
2996 }
2997
Ken Sumrall29d8da82011-05-18 17:20:07 -07002998 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
2999 if (!strcmp(fuse_sdcard, "true")) {
3000 /* This is a device using the fuse layer to emulate the sdcard semantics
3001 * on top of the userdata partition. vold does not manage it, it is managed
3002 * by the sdcard service. The sdcard service was killed by the property trigger
3003 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
3004 * unlike the case for vold managed devices above.
3005 */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07003006 if (wait_and_unmount(sd_mnt_point, false)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07003007 goto error_shutting_down;
3008 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08003009 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003010
3011 /* Now unmount the /data partition. */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07003012 if (wait_and_unmount(DATA_MNT_POINT, false)) {
JP Abgrall502dc742013-11-01 13:06:20 -07003013 if (allow_reboot) {
3014 goto error_shutting_down;
3015 } else {
3016 goto error_unencrypted;
3017 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003018 }
3019
3020 /* Do extra work for a better UX when doing the long inplace encryption */
3021 if (how == CRYPTO_ENABLE_INPLACE) {
3022 /* Now that /data is unmounted, we need to mount a tmpfs
3023 * /data, set a property saying we're doing inplace encryption,
3024 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003025 */
Ken Sumralle5032c42012-04-01 23:58:44 -07003026 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003027 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003028 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003029 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08003030 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003031
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003032 /* restart the framework. */
3033 /* Create necessary paths on /data */
3034 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003035 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003036 }
3037
Ken Sumrall92736ef2012-10-17 20:57:14 -07003038 /* Ugh, shutting down the framework is not synchronous, so until it
3039 * can be fixed, this horrible hack will wait a moment for it all to
3040 * shut down before proceeding. Without it, some devices cannot
3041 * restart the graphics services.
3042 */
3043 sleep(2);
3044
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003045 /* startup service classes main and late_start */
3046 property_set("vold.decrypt", "trigger_restart_min_framework");
3047 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003048
Ken Sumrall7df84122011-01-18 14:04:08 -08003049 /* OK, the framework is restarted and will soon be showing a
3050 * progress bar. Time to setup an encrypted mapping, and
3051 * either write a new filesystem, or encrypt in place updating
3052 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003053 */
3054 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003055
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003056 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003057 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence87999172014-02-20 12:21:31 -08003058 if (previously_encrypted_upto == 0) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07003059 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
3060 goto error_shutting_down;
3061 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003062
Paul Lawrence87999172014-02-20 12:21:31 -08003063 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
3064 crypt_ftr.fs_size = nr_sec
3065 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
3066 } else {
3067 crypt_ftr.fs_size = nr_sec;
3068 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07003069 /* At this point, we are in an inconsistent state. Until we successfully
3070 complete encryption, a reboot will leave us broken. So mark the
3071 encryption failed in case that happens.
3072 On successfully completing encryption, remove this flag */
3073 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence87999172014-02-20 12:21:31 -08003074 crypt_ftr.crypt_type = crypt_type;
3075 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003076
Paul Lawrence87999172014-02-20 12:21:31 -08003077 /* Make an encrypted master key */
3078 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
3079 SLOGE("Cannot create encrypted master key\n");
3080 goto error_shutting_down;
3081 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003082
Paul Lawrence87999172014-02-20 12:21:31 -08003083 /* Write the key to the end of the partition */
3084 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003085
Paul Lawrence87999172014-02-20 12:21:31 -08003086 /* If any persistent data has been remembered, save it.
3087 * If none, create a valid empty table and save that.
3088 */
3089 if (!persist_data) {
3090 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
3091 if (pdata) {
3092 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
3093 persist_data = pdata;
3094 }
3095 }
3096 if (persist_data) {
3097 save_persistent_data();
3098 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003099 }
3100
Paul Lawrenced0c7b172014-08-08 14:28:10 -07003101 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07003102 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
3103 "userdata");
3104
Paul Lawrence87999172014-02-20 12:21:31 -08003105 /* If we are continuing, check checksums match */
3106 rc = 0;
3107 if (previously_encrypted_upto) {
3108 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
3109 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07003110
Paul Lawrence87999172014-02-20 12:21:31 -08003111 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
3112 sizeof(hash_first_block)) != 0) {
3113 SLOGE("Checksums do not match - trigger wipe");
3114 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003115 }
3116 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003117
Paul Lawrence87999172014-02-20 12:21:31 -08003118 if (!rc) {
3119 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
3120 crypto_blkdev, real_blkdev,
3121 previously_encrypted_upto);
3122 }
3123
3124 /* Calculate checksum if we are not finished */
Paul Lawrence73d7a022014-06-09 14:10:09 -07003125 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003126 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
3127 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07003128 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08003129 SLOGE("Error calculating checksum for continuing encryption");
3130 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003131 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003132 }
3133
3134 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003135 delete_crypto_blk_dev("userdata");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003136
3137 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003138
3139 if (! rc) {
3140 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003141 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08003142
Paul Lawrence6bfed202014-07-28 12:47:22 -07003143 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003144 SLOGD("Encrypted up to sector %lld - will continue after reboot",
3145 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07003146 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08003147 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07003148
Paul Lawrence6bfed202014-07-28 12:47:22 -07003149 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08003150
Paul Lawrence73d7a022014-06-09 14:10:09 -07003151 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003152 char value[PROPERTY_VALUE_MAX];
3153 property_get("ro.crypto.state", value, "");
3154 if (!strcmp(value, "")) {
3155 /* default encryption - continue first boot sequence */
3156 property_set("ro.crypto.state", "encrypted");
3157 release_wake_lock(lockid);
3158 cryptfs_check_passwd(DEFAULT_PASSWORD);
3159 cryptfs_restart_internal(1);
3160 return 0;
3161 } else {
3162 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08003163 cryptfs_reboot(reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003164 }
Paul Lawrence87999172014-02-20 12:21:31 -08003165 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003166 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Paul Lawrence87999172014-02-20 12:21:31 -08003167 cryptfs_reboot(shutdown);
3168 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003169 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003170 char value[PROPERTY_VALUE_MAX];
3171
Ken Sumrall319369a2012-06-27 16:30:18 -07003172 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003173 if (!strcmp(value, "1")) {
3174 /* wipe data if encryption failed */
3175 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
3176 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07003177 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003178 if (fd >= 0) {
Jeff Sharkeydd1a8042014-09-24 11:46:51 -07003179 write(fd, "--wipe_data\n", strlen("--wipe_data\n") + 1);
3180 write(fd, "--reason=cryptfs_enable_internal\n", strlen("--reason=cryptfs_enable_internal\n") + 1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003181 close(fd);
3182 } else {
3183 SLOGE("could not open /cache/recovery/command\n");
3184 }
Paul Lawrence87999172014-02-20 12:21:31 -08003185 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003186 } else {
3187 /* set property to trigger dialog */
3188 property_set("vold.encrypt_progress", "error_partially_encrypted");
3189 release_wake_lock(lockid);
3190 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003191 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003192 }
3193
Ken Sumrall3ed82362011-01-28 23:31:16 -08003194 /* hrm, the encrypt step claims success, but the reboot failed.
3195 * This should not happen.
3196 * Set the property and return. Hope the framework can deal with it.
3197 */
3198 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003199 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003200 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08003201
3202error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07003203 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003204 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003205 if (lockid[0]) {
3206 release_wake_lock(lockid);
3207 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003208 return -1;
3209
3210error_shutting_down:
3211 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3212 * but the framework is stopped and not restarted to show the error, so it's up to
3213 * vold to restart the system.
3214 */
3215 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08003216 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003217
3218 /* shouldn't get here */
3219 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003220 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003221 if (lockid[0]) {
3222 release_wake_lock(lockid);
3223 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003224 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003225}
3226
Paul Lawrence45f10532014-04-04 18:11:56 +00003227int cryptfs_enable(char *howarg, int type, char *passwd, int allow_reboot)
Paul Lawrence13486032014-02-03 13:28:11 -08003228{
Paul Lawrencefc615042014-10-04 15:32:29 -07003229 char* adjusted_passwd = adjust_passwd(passwd);
3230 if (adjusted_passwd) {
3231 passwd = adjusted_passwd;
3232 }
3233
3234 int rc = cryptfs_enable_internal(howarg, type, passwd, allow_reboot);
3235
3236 free(adjusted_passwd);
3237 return rc;
Paul Lawrence13486032014-02-03 13:28:11 -08003238}
3239
3240int cryptfs_enable_default(char *howarg, int allow_reboot)
3241{
3242 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
3243 DEFAULT_PASSWORD, allow_reboot);
3244}
3245
3246int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003247{
3248 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003249
3250 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003251 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003252 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003253 return -1;
3254 }
3255
Paul Lawrencef4faa572014-01-29 13:31:03 -08003256 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3257 SLOGE("Invalid crypt_type %d", crypt_type);
3258 return -1;
3259 }
3260
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003261 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003262 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003263 SLOGE("Error getting crypt footer and key");
3264 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003265 }
3266
Paul Lawrencef4faa572014-01-29 13:31:03 -08003267 crypt_ftr.crypt_type = crypt_type;
3268
Paul Lawrencefc615042014-10-04 15:32:29 -07003269 char* adjusted_passwd = adjust_passwd(newpw);
3270 if (adjusted_passwd) {
3271 newpw = adjusted_passwd;
3272 }
3273
Paul Lawrencef4faa572014-01-29 13:31:03 -08003274 encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
3275 : newpw,
3276 crypt_ftr.salt,
3277 saved_master_key,
3278 crypt_ftr.master_key,
3279 &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003280
Jason parks70a4b3f2011-01-28 10:10:47 -06003281 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003282 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003283
Paul Lawrencefc615042014-10-04 15:32:29 -07003284 free(adjusted_passwd);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003285 return 0;
3286}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003287
3288static int persist_get_key(char *fieldname, char *value)
3289{
3290 unsigned int i;
3291
3292 if (persist_data == NULL) {
3293 return -1;
3294 }
3295 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3296 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3297 /* We found it! */
3298 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3299 return 0;
3300 }
3301 }
3302
3303 return -1;
3304}
3305
3306static int persist_set_key(char *fieldname, char *value, int encrypted)
3307{
3308 unsigned int i;
3309 unsigned int num;
3310 struct crypt_mnt_ftr crypt_ftr;
3311 unsigned int max_persistent_entries;
3312 unsigned int dsize;
3313
3314 if (persist_data == NULL) {
3315 return -1;
3316 }
3317
3318 /* If encrypted, use the values from the crypt_ftr, otherwise
3319 * use the values for the current spec.
3320 */
3321 if (encrypted) {
3322 if(get_crypt_ftr_and_key(&crypt_ftr)) {
3323 return -1;
3324 }
3325 dsize = crypt_ftr.persist_data_size;
3326 } else {
3327 dsize = CRYPT_PERSIST_DATA_SIZE;
3328 }
3329 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3330 sizeof(struct crypt_persist_entry);
3331
3332 num = persist_data->persist_valid_entries;
3333
3334 for (i = 0; i < num; i++) {
3335 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3336 /* We found an existing entry, update it! */
3337 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3338 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3339 return 0;
3340 }
3341 }
3342
3343 /* We didn't find it, add it to the end, if there is room */
3344 if (persist_data->persist_valid_entries < max_persistent_entries) {
3345 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3346 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3347 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3348 persist_data->persist_valid_entries++;
3349 return 0;
3350 }
3351
3352 return -1;
3353}
3354
3355/* Return the value of the specified field. */
3356int cryptfs_getfield(char *fieldname, char *value, int len)
3357{
3358 char temp_value[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003359 /* 0 is success, 1 is not encrypted,
3360 * -1 is value not set, -2 is any other error
3361 */
3362 int rc = -2;
3363
3364 if (persist_data == NULL) {
3365 load_persistent_data();
3366 if (persist_data == NULL) {
3367 SLOGE("Getfield error, cannot load persistent data");
3368 goto out;
3369 }
3370 }
3371
3372 if (!persist_get_key(fieldname, temp_value)) {
3373 /* We found it, copy it to the caller's buffer and return */
3374 strlcpy(value, temp_value, len);
3375 rc = 0;
3376 } else {
3377 /* Sadness, it's not there. Return the error */
3378 rc = -1;
3379 }
3380
3381out:
3382 return rc;
3383}
3384
3385/* Set the value of the specified field. */
3386int cryptfs_setfield(char *fieldname, char *value)
3387{
Ken Sumrall160b4d62013-04-22 12:15:39 -07003388 char encrypted_state[PROPERTY_VALUE_MAX];
3389 /* 0 is success, -1 is an error */
3390 int rc = -1;
3391 int encrypted = 0;
3392
3393 if (persist_data == NULL) {
3394 load_persistent_data();
3395 if (persist_data == NULL) {
3396 SLOGE("Setfield error, cannot load persistent data");
3397 goto out;
3398 }
3399 }
3400
3401 property_get("ro.crypto.state", encrypted_state, "");
3402 if (!strcmp(encrypted_state, "encrypted") ) {
3403 encrypted = 1;
3404 }
3405
3406 if (persist_set_key(fieldname, value, encrypted)) {
3407 goto out;
3408 }
3409
3410 /* If we are running encrypted, save the persistent data now */
3411 if (encrypted) {
3412 if (save_persistent_data()) {
3413 SLOGE("Setfield error, cannot save persistent data");
3414 goto out;
3415 }
3416 }
3417
3418 rc = 0;
3419
3420out:
3421 return rc;
3422}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003423
3424/* Checks userdata. Attempt to mount the volume if default-
3425 * encrypted.
3426 * On success trigger next init phase and return 0.
3427 * Currently do not handle failure - see TODO below.
3428 */
3429int cryptfs_mount_default_encrypted(void)
3430{
3431 char decrypt_state[PROPERTY_VALUE_MAX];
3432 property_get("vold.decrypt", decrypt_state, "0");
3433 if (!strcmp(decrypt_state, "0")) {
3434 SLOGE("Not encrypted - should not call here");
3435 } else {
3436 int crypt_type = cryptfs_get_password_type();
3437 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3438 SLOGE("Bad crypt type - error");
3439 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3440 SLOGD("Password is not default - "
3441 "starting min framework to prompt");
3442 property_set("vold.decrypt", "trigger_restart_min_framework");
3443 return 0;
3444 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3445 SLOGD("Password is default - restarting filesystem");
3446 cryptfs_restart_internal(0);
3447 return 0;
3448 } else {
3449 SLOGE("Encrypted, default crypt type but can't decrypt");
3450 }
3451 }
3452
Paul Lawrence6bfed202014-07-28 12:47:22 -07003453 /** Corrupt. Allow us to boot into framework, which will detect bad
3454 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003455 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003456 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003457 return 0;
3458}
3459
3460/* Returns type of the password, default, pattern, pin or password.
3461 */
3462int cryptfs_get_password_type(void)
3463{
3464 struct crypt_mnt_ftr crypt_ftr;
3465
3466 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3467 SLOGE("Error getting crypt footer and key\n");
3468 return -1;
3469 }
3470
Paul Lawrence6bfed202014-07-28 12:47:22 -07003471 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3472 return -1;
3473 }
3474
Paul Lawrencef4faa572014-01-29 13:31:03 -08003475 return crypt_ftr.crypt_type;
3476}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003477
Paul Lawrence399317e2014-03-10 13:20:50 -07003478char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003479{
Paul Lawrence399317e2014-03-10 13:20:50 -07003480 struct timespec now;
3481 clock_gettime(CLOCK_MONOTONIC, &now);
3482 if (now.tv_sec < password_expiry_time) {
3483 return password;
3484 } else {
3485 cryptfs_clear_password();
3486 return 0;
3487 }
3488}
3489
3490void cryptfs_clear_password()
3491{
3492 if (password) {
3493 size_t len = strlen(password);
3494 memset(password, 0, len);
3495 free(password);
3496 password = 0;
3497 password_expiry_time = 0;
3498 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003499}