blob: f6ea9aae267c685d20ba469d3328c96686030842 [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>
Rubin Xu85c01f92014-10-13 12:49:54 +010045#include <math.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080046#include "cryptfs.h"
47#define LOG_TAG "Cryptfs"
48#include "cutils/log.h"
49#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070050#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080051#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070052#include <logwrap/logwrap.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070053#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070054#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070055#include "crypto_scrypt.h"
Paul Lawrenceae59fe62014-01-21 08:23:27 -080056#include "ext4_utils.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000057#include "f2fs_sparseblock.h"
Paul Lawrence87999172014-02-20 12:21:31 -080058#include "CheckBattery.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080059#include "Process.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080060
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070061#include <hardware/keymaster.h>
62
Mark Salyzyn3e971272014-01-21 13:27:04 -080063#define UNUSED __attribute__((unused))
64
Mark Salyzyn5eecc442014-02-12 14:16:14 -080065#define UNUSED __attribute__((unused))
66
Ajay Dudani87701e22014-09-17 21:02:52 -070067#ifdef CONFIG_HW_DISK_ENCRYPTION
68#include "cryptfs_hw.h"
69#endif
70
Ken Sumrall8f869aa2010-12-03 03:47:09 -080071#define DM_CRYPT_BUF_SIZE 4096
72
Jason parks70a4b3f2011-01-28 10:10:47 -060073#define HASH_COUNT 2000
74#define KEY_LEN_BYTES 16
75#define IV_LEN_BYTES 16
76
Ken Sumrall29d8da82011-05-18 17:20:07 -070077#define KEY_IN_FOOTER "footer"
78
Paul Lawrencef4faa572014-01-29 13:31:03 -080079// "default_password" encoded into hex (d=0x64 etc)
80#define DEFAULT_PASSWORD "64656661756c745f70617373776f7264"
81
Ken Sumrall29d8da82011-05-18 17:20:07 -070082#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070083#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070084
Ken Sumralle919efe2012-09-29 17:07:41 -070085#define TABLE_LOAD_RETRIES 10
86
Shawn Willden47ba10d2014-09-03 17:07:06 -060087#define RSA_KEY_SIZE 2048
88#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
89#define RSA_EXPONENT 0x10001
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070090
Paul Lawrence8e3f4512014-09-08 10:11:17 -070091#define RETRY_MOUNT_ATTEMPTS 10
92#define RETRY_MOUNT_DELAY_SECONDS 1
93
Ken Sumrall8f869aa2010-12-03 03:47:09 -080094char *me = "cryptfs";
95
Jason parks70a4b3f2011-01-28 10:10:47 -060096static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070097static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060098static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -070099static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800100
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700101static int keymaster_init(keymaster_device_t **keymaster_dev)
102{
103 int rc;
104
105 const hw_module_t* mod;
106 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
107 if (rc) {
108 ALOGE("could not find any keystore module");
109 goto out;
110 }
111
112 rc = keymaster_open(mod, keymaster_dev);
113 if (rc) {
114 ALOGE("could not open keymaster device in %s (%s)",
115 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
116 goto out;
117 }
118
119 return 0;
120
121out:
122 *keymaster_dev = NULL;
123 return rc;
124}
125
126/* Should we use keymaster? */
127static int keymaster_check_compatibility()
128{
129 keymaster_device_t *keymaster_dev = 0;
130 int rc = 0;
131
132 if (keymaster_init(&keymaster_dev)) {
133 SLOGE("Failed to init keymaster");
134 rc = -1;
135 goto out;
136 }
137
Paul Lawrence8c008392014-05-06 14:02:48 -0700138 SLOGI("keymaster version is %d", keymaster_dev->common.module->module_api_version);
139
140 if (keymaster_dev->common.module->module_api_version
141 < KEYMASTER_MODULE_API_VERSION_0_3) {
142 rc = 0;
143 goto out;
144 }
145
Shawn Willden7c49ab02014-10-30 08:12:32 -0600146 if (!(keymaster_dev->flags & KEYMASTER_SOFTWARE_ONLY) &&
147 (keymaster_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE)) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700148 rc = 1;
149 }
150
151out:
152 keymaster_close(keymaster_dev);
153 return rc;
154}
155
156/* Create a new keymaster key and store it in this footer */
157static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
158{
159 uint8_t* key = 0;
160 keymaster_device_t *keymaster_dev = 0;
161
162 if (keymaster_init(&keymaster_dev)) {
163 SLOGE("Failed to init keymaster");
164 return -1;
165 }
166
167 int rc = 0;
168
169 keymaster_rsa_keygen_params_t params;
170 memset(&params, '\0', sizeof(params));
Shawn Willden47ba10d2014-09-03 17:07:06 -0600171 params.public_exponent = RSA_EXPONENT;
172 params.modulus_size = RSA_KEY_SIZE;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700173
174 size_t key_size;
175 if (keymaster_dev->generate_keypair(keymaster_dev, TYPE_RSA, &params,
176 &key, &key_size)) {
177 SLOGE("Failed to generate keypair");
178 rc = -1;
179 goto out;
180 }
181
182 if (key_size > KEYMASTER_BLOB_SIZE) {
183 SLOGE("Keymaster key too large for crypto footer");
184 rc = -1;
185 goto out;
186 }
187
188 memcpy(ftr->keymaster_blob, key, key_size);
189 ftr->keymaster_blob_size = key_size;
190
191out:
192 keymaster_close(keymaster_dev);
193 free(key);
194 return rc;
195}
196
Shawn Willdene17a9c42014-09-08 13:04:08 -0600197/* This signs the given object using the keymaster key. */
198static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600199 const unsigned char *object,
200 const size_t object_size,
201 unsigned char **signature,
202 size_t *signature_size)
203{
204 int rc = 0;
205 keymaster_device_t *keymaster_dev = 0;
206 if (keymaster_init(&keymaster_dev)) {
207 SLOGE("Failed to init keymaster");
208 return -1;
209 }
210
211 /* We currently set the digest type to DIGEST_NONE because it's the
212 * only supported value for keymaster. A similar issue exists with
213 * PADDING_NONE. Long term both of these should likely change.
214 */
215 keymaster_rsa_sign_params_t params;
216 params.digest_type = DIGEST_NONE;
217 params.padding_type = PADDING_NONE;
218
219 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600220 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600221 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600222
Shawn Willdene17a9c42014-09-08 13:04:08 -0600223 // To sign a message with RSA, the message must satisfy two
224 // constraints:
225 //
226 // 1. The message, when interpreted as a big-endian numeric value, must
227 // be strictly less than the public modulus of the RSA key. Note
228 // that because the most significant bit of the public modulus is
229 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
230 // key), an n-bit message with most significant bit 0 always
231 // satisfies this requirement.
232 //
233 // 2. The message must have the same length in bits as the public
234 // modulus of the RSA key. This requirement isn't mathematically
235 // necessary, but is necessary to ensure consistency in
236 // implementations.
237 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600238 case KDF_SCRYPT_KEYMASTER:
239 // This ensures the most significant byte of the signed message
240 // is zero. We could have zero-padded to the left instead, but
241 // this approach is slightly more robust against changes in
242 // object size. However, it's still broken (but not unusably
243 // so) because we really should be using a proper RSA padding
244 // function, such as OAEP.
245 //
246 // TODO(paullawrence): When keymaster 0.4 is available, change
247 // this to use the padding options it provides.
248 memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
249 SLOGI("Signing safely-padded object");
250 break;
251 default:
252 SLOGE("Unknown KDF type %d", ftr->kdf_type);
253 return -1;
254 }
255
Shawn Willden47ba10d2014-09-03 17:07:06 -0600256 rc = keymaster_dev->sign_data(keymaster_dev,
257 &params,
258 ftr->keymaster_blob,
259 ftr->keymaster_blob_size,
260 to_sign,
Shawn Willdene17a9c42014-09-08 13:04:08 -0600261 to_sign_size,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600262 signature,
263 signature_size);
264
265 keymaster_close(keymaster_dev);
266 return rc;
267}
268
Paul Lawrence399317e2014-03-10 13:20:50 -0700269/* Store password when userdata is successfully decrypted and mounted.
270 * Cleared by cryptfs_clear_password
271 *
272 * To avoid a double prompt at boot, we need to store the CryptKeeper
273 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
274 * Since the entire framework is torn down and rebuilt after encryption,
275 * we have to use a daemon or similar to store the password. Since vold
276 * is secured against IPC except from system processes, it seems a reasonable
277 * place to store this.
278 *
279 * password should be cleared once it has been used.
280 *
281 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800282 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700283static char* password = 0;
284static int password_expiry_time = 0;
285static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800286
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800287extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800288
Paul Lawrence87999172014-02-20 12:21:31 -0800289enum RebootType {reboot, recovery, shutdown};
290static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700291{
Paul Lawrence87999172014-02-20 12:21:31 -0800292 switch(rt) {
293 case reboot:
294 property_set(ANDROID_RB_PROPERTY, "reboot");
295 break;
296
297 case recovery:
298 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
299 break;
300
301 case shutdown:
302 property_set(ANDROID_RB_PROPERTY, "shutdown");
303 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700304 }
Paul Lawrence87999172014-02-20 12:21:31 -0800305
Ken Sumralladfba362013-06-04 16:37:52 -0700306 sleep(20);
307
308 /* Shouldn't get here, reboot should happen before sleep times out */
309 return;
310}
311
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800312static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
313{
314 memset(io, 0, dataSize);
315 io->data_size = dataSize;
316 io->data_start = sizeof(struct dm_ioctl);
317 io->version[0] = 4;
318 io->version[1] = 0;
319 io->version[2] = 0;
320 io->flags = flags;
321 if (name) {
322 strncpy(io->name, name, sizeof(io->name));
323 }
324}
325
Kenny Rootc4c70f12013-06-14 12:11:38 -0700326/**
327 * Gets the default device scrypt parameters for key derivation time tuning.
328 * The parameters should lead to about one second derivation time for the
329 * given device.
330 */
331static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
332 const int default_params[] = SCRYPT_DEFAULTS;
333 int params[] = SCRYPT_DEFAULTS;
334 char paramstr[PROPERTY_VALUE_MAX];
335 char *token;
336 char *saveptr;
337 int i;
338
339 property_get(SCRYPT_PROP, paramstr, "");
340 if (paramstr[0] != '\0') {
341 /*
342 * The token we're looking for should be three integers separated by
343 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
344 */
Kenny Root2947e342013-08-14 15:54:49 -0700345 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
346 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700347 i++, token = strtok_r(NULL, ":", &saveptr)) {
348 char *endptr;
349 params[i] = strtol(token, &endptr, 10);
350
351 /*
352 * Check that there was a valid number and it's 8-bit. If not,
353 * break out and the end check will take the default values.
354 */
355 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
356 break;
357 }
358 }
359
360 /*
361 * If there were not enough tokens or a token was malformed (not an
362 * integer), it will end up here and the default parameters can be
363 * taken.
364 */
365 if ((i != 3) || (token != NULL)) {
366 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
367 memcpy(params, default_params, sizeof(params));
368 }
369 }
370
371 ftr->N_factor = params[0];
372 ftr->r_factor = params[1];
373 ftr->p_factor = params[2];
374}
375
Ken Sumrall3ed82362011-01-28 23:31:16 -0800376static unsigned int get_fs_size(char *dev)
377{
378 int fd, block_size;
379 struct ext4_super_block sb;
380 off64_t len;
381
382 if ((fd = open(dev, O_RDONLY)) < 0) {
383 SLOGE("Cannot open device to get filesystem size ");
384 return 0;
385 }
386
387 if (lseek64(fd, 1024, SEEK_SET) < 0) {
388 SLOGE("Cannot seek to superblock");
389 return 0;
390 }
391
392 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
393 SLOGE("Cannot read superblock");
394 return 0;
395 }
396
397 close(fd);
398
Daniel Rosenberge82df162014-08-15 22:19:23 +0000399 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
400 SLOGE("Not a valid ext4 superblock");
401 return 0;
402 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800403 block_size = 1024 << sb.s_log_block_size;
404 /* compute length in bytes */
405 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
406
407 /* return length in sectors */
408 return (unsigned int) (len / 512);
409}
410
Ken Sumrall160b4d62013-04-22 12:15:39 -0700411static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
412{
413 static int cached_data = 0;
414 static off64_t cached_off = 0;
415 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
416 int fd;
417 char key_loc[PROPERTY_VALUE_MAX];
418 char real_blkdev[PROPERTY_VALUE_MAX];
419 unsigned int nr_sec;
420 int rc = -1;
421
422 if (!cached_data) {
423 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
424
425 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
426 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
427 SLOGE("Cannot open real block device %s\n", real_blkdev);
428 return -1;
429 }
430
431 if ((nr_sec = get_blkdev_size(fd))) {
432 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
433 * encryption info footer and key, and plenty of bytes to spare for future
434 * growth.
435 */
436 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
437 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
438 cached_data = 1;
439 } else {
440 SLOGE("Cannot get size of block device %s\n", real_blkdev);
441 }
442 close(fd);
443 } else {
444 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
445 cached_off = 0;
446 cached_data = 1;
447 }
448 }
449
450 if (cached_data) {
451 if (metadata_fname) {
452 *metadata_fname = cached_metadata_fname;
453 }
454 if (off) {
455 *off = cached_off;
456 }
457 rc = 0;
458 }
459
460 return rc;
461}
462
Ken Sumralle8744072011-01-18 22:01:55 -0800463/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800464 * update the failed mount count but not change the key.
465 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700466static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800467{
468 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800469 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700470 /* starting_off is set to the SEEK_SET offset
471 * where the crypto structure starts
472 */
473 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800474 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700475 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700476 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800477
Ken Sumrall160b4d62013-04-22 12:15:39 -0700478 if (get_crypt_ftr_info(&fname, &starting_off)) {
479 SLOGE("Unable to get crypt_ftr_info\n");
480 return -1;
481 }
482 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700483 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700484 return -1;
485 }
Ken Sumralle550f782013-08-20 13:48:23 -0700486 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
487 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700488 return -1;
489 }
490
491 /* Seek to the start of the crypt footer */
492 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
493 SLOGE("Cannot seek to real block device footer\n");
494 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800495 }
496
497 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
498 SLOGE("Cannot write real block device footer\n");
499 goto errout;
500 }
501
Ken Sumrall3be890f2011-09-14 16:53:46 -0700502 fstat(fd, &statbuf);
503 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700504 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700505 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800506 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800507 goto errout;
508 }
509 }
510
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800511 /* Success! */
512 rc = 0;
513
514errout:
515 close(fd);
516 return rc;
517
518}
519
Ken Sumrall160b4d62013-04-22 12:15:39 -0700520static inline int unix_read(int fd, void* buff, int len)
521{
522 return TEMP_FAILURE_RETRY(read(fd, buff, len));
523}
524
525static inline int unix_write(int fd, const void* buff, int len)
526{
527 return TEMP_FAILURE_RETRY(write(fd, buff, len));
528}
529
530static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
531{
532 memset(pdata, 0, len);
533 pdata->persist_magic = PERSIST_DATA_MAGIC;
534 pdata->persist_valid_entries = 0;
535}
536
537/* A routine to update the passed in crypt_ftr to the lastest version.
538 * fd is open read/write on the device that holds the crypto footer and persistent
539 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
540 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
541 */
542static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
543{
Kenny Root7434b312013-06-14 11:29:53 -0700544 int orig_major = crypt_ftr->major_version;
545 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700546
Kenny Root7434b312013-06-14 11:29:53 -0700547 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
548 struct crypt_persist_data *pdata;
549 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700550
Kenny Rootc4c70f12013-06-14 12:11:38 -0700551 SLOGW("upgrading crypto footer to 1.1");
552
Kenny Root7434b312013-06-14 11:29:53 -0700553 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
554 if (pdata == NULL) {
555 SLOGE("Cannot allocate persisent data\n");
556 return;
557 }
558 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
559
560 /* Need to initialize the persistent data area */
561 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
562 SLOGE("Cannot seek to persisent data offset\n");
563 return;
564 }
565 /* Write all zeros to the first copy, making it invalid */
566 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
567
568 /* Write a valid but empty structure to the second copy */
569 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
570 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
571
572 /* Update the footer */
573 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
574 crypt_ftr->persist_data_offset[0] = pdata_offset;
575 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
576 crypt_ftr->minor_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700577 }
578
Paul Lawrencef4faa572014-01-29 13:31:03 -0800579 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700580 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800581 /* But keep the old kdf_type.
582 * It will get updated later to KDF_SCRYPT after the password has been verified.
583 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700584 crypt_ftr->kdf_type = KDF_PBKDF2;
585 get_device_scrypt_params(crypt_ftr);
586 crypt_ftr->minor_version = 2;
587 }
588
Paul Lawrencef4faa572014-01-29 13:31:03 -0800589 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
590 SLOGW("upgrading crypto footer to 1.3");
591 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
592 crypt_ftr->minor_version = 3;
593 }
594
Kenny Root7434b312013-06-14 11:29:53 -0700595 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
596 if (lseek64(fd, offset, SEEK_SET) == -1) {
597 SLOGE("Cannot seek to crypt footer\n");
598 return;
599 }
600 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700601 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700602}
603
604
605static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800606{
607 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800608 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700609 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800610 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700611 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700612 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800613
Ken Sumrall160b4d62013-04-22 12:15:39 -0700614 if (get_crypt_ftr_info(&fname, &starting_off)) {
615 SLOGE("Unable to get crypt_ftr_info\n");
616 return -1;
617 }
618 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700619 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700620 return -1;
621 }
622 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700623 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700624 return -1;
625 }
626
627 /* Make sure it's 16 Kbytes in length */
628 fstat(fd, &statbuf);
629 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
630 SLOGE("footer file %s is not the expected size!\n", fname);
631 goto errout;
632 }
633
634 /* Seek to the start of the crypt footer */
635 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
636 SLOGE("Cannot seek to real block device footer\n");
637 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800638 }
639
640 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
641 SLOGE("Cannot read real block device footer\n");
642 goto errout;
643 }
644
645 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700646 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800647 goto errout;
648 }
649
Kenny Rootc96a5f82013-06-14 12:08:28 -0700650 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
651 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
652 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800653 goto errout;
654 }
655
Kenny Rootc96a5f82013-06-14 12:08:28 -0700656 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
657 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
658 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800659 }
660
Ken Sumrall160b4d62013-04-22 12:15:39 -0700661 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
662 * copy on disk before returning.
663 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700664 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700665 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800666 }
667
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800668 /* Success! */
669 rc = 0;
670
671errout:
672 close(fd);
673 return rc;
674}
675
Ken Sumrall160b4d62013-04-22 12:15:39 -0700676static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
677{
678 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
679 crypt_ftr->persist_data_offset[1]) {
680 SLOGE("Crypt_ftr persist data regions overlap");
681 return -1;
682 }
683
684 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
685 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
686 return -1;
687 }
688
689 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
690 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
691 CRYPT_FOOTER_OFFSET) {
692 SLOGE("Persistent data extends past crypto footer");
693 return -1;
694 }
695
696 return 0;
697}
698
699static int load_persistent_data(void)
700{
701 struct crypt_mnt_ftr crypt_ftr;
702 struct crypt_persist_data *pdata = NULL;
703 char encrypted_state[PROPERTY_VALUE_MAX];
704 char *fname;
705 int found = 0;
706 int fd;
707 int ret;
708 int i;
709
710 if (persist_data) {
711 /* Nothing to do, we've already loaded or initialized it */
712 return 0;
713 }
714
715
716 /* If not encrypted, just allocate an empty table and initialize it */
717 property_get("ro.crypto.state", encrypted_state, "");
718 if (strcmp(encrypted_state, "encrypted") ) {
719 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
720 if (pdata) {
721 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
722 persist_data = pdata;
723 return 0;
724 }
725 return -1;
726 }
727
728 if(get_crypt_ftr_and_key(&crypt_ftr)) {
729 return -1;
730 }
731
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700732 if ((crypt_ftr.major_version < 1)
733 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700734 SLOGE("Crypt_ftr version doesn't support persistent data");
735 return -1;
736 }
737
738 if (get_crypt_ftr_info(&fname, NULL)) {
739 return -1;
740 }
741
742 ret = validate_persistent_data_storage(&crypt_ftr);
743 if (ret) {
744 return -1;
745 }
746
747 fd = open(fname, O_RDONLY);
748 if (fd < 0) {
749 SLOGE("Cannot open %s metadata file", fname);
750 return -1;
751 }
752
753 if (persist_data == NULL) {
754 pdata = malloc(crypt_ftr.persist_data_size);
755 if (pdata == NULL) {
756 SLOGE("Cannot allocate memory for persistent data");
757 goto err;
758 }
759 }
760
761 for (i = 0; i < 2; i++) {
762 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
763 SLOGE("Cannot seek to read persistent data on %s", fname);
764 goto err2;
765 }
766 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
767 SLOGE("Error reading persistent data on iteration %d", i);
768 goto err2;
769 }
770 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
771 found = 1;
772 break;
773 }
774 }
775
776 if (!found) {
777 SLOGI("Could not find valid persistent data, creating");
778 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
779 }
780
781 /* Success */
782 persist_data = pdata;
783 close(fd);
784 return 0;
785
786err2:
787 free(pdata);
788
789err:
790 close(fd);
791 return -1;
792}
793
794static int save_persistent_data(void)
795{
796 struct crypt_mnt_ftr crypt_ftr;
797 struct crypt_persist_data *pdata;
798 char *fname;
799 off64_t write_offset;
800 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700801 int fd;
802 int ret;
803
804 if (persist_data == NULL) {
805 SLOGE("No persistent data to save");
806 return -1;
807 }
808
809 if(get_crypt_ftr_and_key(&crypt_ftr)) {
810 return -1;
811 }
812
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700813 if ((crypt_ftr.major_version < 1)
814 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700815 SLOGE("Crypt_ftr version doesn't support persistent data");
816 return -1;
817 }
818
819 ret = validate_persistent_data_storage(&crypt_ftr);
820 if (ret) {
821 return -1;
822 }
823
824 if (get_crypt_ftr_info(&fname, NULL)) {
825 return -1;
826 }
827
828 fd = open(fname, O_RDWR);
829 if (fd < 0) {
830 SLOGE("Cannot open %s metadata file", fname);
831 return -1;
832 }
833
834 pdata = malloc(crypt_ftr.persist_data_size);
835 if (pdata == NULL) {
836 SLOGE("Cannot allocate persistant data");
837 goto err;
838 }
839
840 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
841 SLOGE("Cannot seek to read persistent data on %s", fname);
842 goto err2;
843 }
844
845 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
846 SLOGE("Error reading persistent data before save");
847 goto err2;
848 }
849
850 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
851 /* The first copy is the curent valid copy, so write to
852 * the second copy and erase this one */
853 write_offset = crypt_ftr.persist_data_offset[1];
854 erase_offset = crypt_ftr.persist_data_offset[0];
855 } else {
856 /* The second copy must be the valid copy, so write to
857 * the first copy, and erase the second */
858 write_offset = crypt_ftr.persist_data_offset[0];
859 erase_offset = crypt_ftr.persist_data_offset[1];
860 }
861
862 /* Write the new copy first, if successful, then erase the old copy */
863 if (lseek(fd, write_offset, SEEK_SET) < 0) {
864 SLOGE("Cannot seek to write persistent data");
865 goto err2;
866 }
867 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
868 (int) crypt_ftr.persist_data_size) {
869 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
870 SLOGE("Cannot seek to erase previous persistent data");
871 goto err2;
872 }
873 fsync(fd);
874 memset(pdata, 0, crypt_ftr.persist_data_size);
875 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
876 (int) crypt_ftr.persist_data_size) {
877 SLOGE("Cannot write to erase previous persistent data");
878 goto err2;
879 }
880 fsync(fd);
881 } else {
882 SLOGE("Cannot write to save persistent data");
883 goto err2;
884 }
885
886 /* Success */
887 free(pdata);
888 close(fd);
889 return 0;
890
891err2:
892 free(pdata);
893err:
894 close(fd);
895 return -1;
896}
897
Paul Lawrencef4faa572014-01-29 13:31:03 -0800898static int hexdigit (char c)
899{
900 if (c >= '0' && c <= '9') return c - '0';
901 c = tolower(c);
902 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
903 return -1;
904}
905
906static unsigned char* convert_hex_ascii_to_key(const char* master_key_ascii,
907 unsigned int* out_keysize)
908{
909 unsigned int i;
910 *out_keysize = 0;
911
912 size_t size = strlen (master_key_ascii);
913 if (size % 2) {
914 SLOGE("Trying to convert ascii string of odd length");
915 return NULL;
916 }
917
918 unsigned char* master_key = (unsigned char*) malloc(size / 2);
919 if (master_key == 0) {
920 SLOGE("Cannot allocate");
921 return NULL;
922 }
923
924 for (i = 0; i < size; i += 2) {
925 int high_nibble = hexdigit (master_key_ascii[i]);
926 int low_nibble = hexdigit (master_key_ascii[i + 1]);
927
928 if(high_nibble < 0 || low_nibble < 0) {
929 SLOGE("Invalid hex string");
930 free (master_key);
931 return NULL;
932 }
933
934 master_key[*out_keysize] = high_nibble * 16 + low_nibble;
935 (*out_keysize)++;
936 }
937
938 return master_key;
939}
940
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800941/* Convert a binary key of specified length into an ascii hex string equivalent,
942 * without the leading 0x and with null termination
943 */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800944static void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800945 char *master_key_ascii)
946{
947 unsigned int i, a;
948 unsigned char nibble;
949
950 for (i=0, a=0; i<keysize; i++, a+=2) {
951 /* For each byte, write out two ascii hex digits */
952 nibble = (master_key[i] >> 4) & 0xf;
953 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
954
955 nibble = master_key[i] & 0xf;
956 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
957 }
958
959 /* Add the null termination */
960 master_key_ascii[a] = '\0';
961
962}
963
Ken Sumralldb5e0262013-02-05 17:39:48 -0800964static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
965 char *real_blk_name, const char *name, int fd,
966 char *extra_params)
967{
Dan Albertc07fa3f2014-12-18 10:00:55 -0800968 _Alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800969 struct dm_ioctl *io;
970 struct dm_target_spec *tgt;
971 char *crypt_params;
972 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
973 int i;
974
975 io = (struct dm_ioctl *) buffer;
976
977 /* Load the mapping table for this device */
978 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
979
980 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
981 io->target_count = 1;
982 tgt->status = 0;
983 tgt->sector_start = 0;
984 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -0700985#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -0800986 if (!strcmp((char *)crypt_ftr->crypto_type_name, "aes-xts")) {
987 strlcpy(tgt->target_type, "req-crypt", DM_MAX_TYPE_NAME);
988 }
989 else {
990 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
991 }
Ajay Dudani87701e22014-09-17 21:02:52 -0700992#else
993 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
994#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -0800995
996 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
997 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
998 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
999 master_key_ascii, real_blk_name, extra_params);
1000 crypt_params += strlen(crypt_params) + 1;
1001 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1002 tgt->next = crypt_params - buffer;
1003
1004 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1005 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
1006 break;
1007 }
1008 usleep(500000);
1009 }
1010
1011 if (i == TABLE_LOAD_RETRIES) {
1012 /* We failed to load the table, return an error */
1013 return -1;
1014 } else {
1015 return i + 1;
1016 }
1017}
1018
1019
1020static int get_dm_crypt_version(int fd, const char *name, int *version)
1021{
1022 char buffer[DM_CRYPT_BUF_SIZE];
1023 struct dm_ioctl *io;
1024 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001025
1026 io = (struct dm_ioctl *) buffer;
1027
1028 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1029
1030 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1031 return -1;
1032 }
1033
1034 /* Iterate over the returned versions, looking for name of "crypt".
1035 * When found, get and return the version.
1036 */
1037 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1038 while (v->next) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001039#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001040 if (! strcmp(v->name, "crypt") || ! strcmp(v->name, "req-crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001041#else
Ken Sumralldb5e0262013-02-05 17:39:48 -08001042 if (! strcmp(v->name, "crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001043#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001044 /* We found the crypt driver, return the version, and get out */
1045 version[0] = v->version[0];
1046 version[1] = v->version[1];
1047 version[2] = v->version[2];
1048 return 0;
1049 }
1050 v = (struct dm_target_versions *)(((char *)v) + v->next);
1051 }
1052
1053 return -1;
1054}
1055
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001056static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -07001057 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001058{
1059 char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001060 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001061 unsigned int minor;
Ajay Dudani87701e22014-09-17 21:02:52 -07001062 int fd=0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001063 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001064 int version[3];
1065 char *extra_params;
1066 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001067
1068 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1069 SLOGE("Cannot open device-mapper\n");
1070 goto errout;
1071 }
1072
1073 io = (struct dm_ioctl *) buffer;
1074
1075 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1076 if (ioctl(fd, DM_DEV_CREATE, io)) {
1077 SLOGE("Cannot create dm-crypt device\n");
1078 goto errout;
1079 }
1080
1081 /* Get the device status, in particular, the name of it's device file */
1082 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1083 if (ioctl(fd, DM_DEV_STATUS, io)) {
1084 SLOGE("Cannot retrieve dm-crypt device status\n");
1085 goto errout;
1086 }
1087 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1088 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1089
Ken Sumralldb5e0262013-02-05 17:39:48 -08001090 extra_params = "";
1091 if (! get_dm_crypt_version(fd, name, version)) {
1092 /* Support for allow_discards was added in version 1.11.0 */
1093 if ((version[0] >= 2) ||
1094 ((version[0] == 1) && (version[1] >= 11))) {
1095 extra_params = "1 allow_discards";
1096 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1097 }
Ken Sumralle919efe2012-09-29 17:07:41 -07001098 }
1099
Ken Sumralldb5e0262013-02-05 17:39:48 -08001100 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1101 fd, extra_params);
1102 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001103 SLOGE("Cannot load dm-crypt mapping table.\n");
1104 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001105 } else if (load_count > 1) {
1106 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001107 }
1108
1109 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -08001110 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001111
1112 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1113 SLOGE("Cannot resume the dm-crypt device\n");
1114 goto errout;
1115 }
1116
1117 /* We made it here with no errors. Woot! */
1118 retval = 0;
1119
1120errout:
1121 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1122
1123 return retval;
1124}
1125
Ken Sumrall29d8da82011-05-18 17:20:07 -07001126static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001127{
1128 int fd;
1129 char buffer[DM_CRYPT_BUF_SIZE];
1130 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001131 int retval = -1;
1132
1133 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1134 SLOGE("Cannot open device-mapper\n");
1135 goto errout;
1136 }
1137
1138 io = (struct dm_ioctl *) buffer;
1139
1140 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1141 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1142 SLOGE("Cannot remove dm-crypt device\n");
1143 goto errout;
1144 }
1145
1146 /* We made it here with no errors. Woot! */
1147 retval = 0;
1148
1149errout:
1150 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1151
1152 return retval;
1153
1154}
1155
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001156static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001157 unsigned char *ikey, void *params UNUSED)
1158{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001159 SLOGI("Using pbkdf2 for cryptfs KDF");
1160
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001161 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001162 unsigned int keysize;
1163 char* master_key = (char*)convert_hex_ascii_to_key(passwd, &keysize);
1164 if (!master_key) return -1;
1165 PKCS5_PBKDF2_HMAC_SHA1(master_key, keysize, salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001166 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001167
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001168 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001169 free (master_key);
1170 return 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001171}
1172
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001173static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001174 unsigned char *ikey, void *params)
1175{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001176 SLOGI("Using scrypt for cryptfs KDF");
1177
Kenny Rootc4c70f12013-06-14 12:11:38 -07001178 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1179
1180 int N = 1 << ftr->N_factor;
1181 int r = 1 << ftr->r_factor;
1182 int p = 1 << ftr->p_factor;
1183
1184 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001185 unsigned int keysize;
1186 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &keysize);
1187 if (!master_key) return -1;
1188 crypto_scrypt(master_key, keysize, salt, SALT_LEN, N, r, p, ikey,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001189 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001190
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001191 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001192 free (master_key);
1193 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001194}
1195
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001196static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1197 unsigned char *ikey, void *params)
1198{
1199 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1200
1201 int rc;
1202 unsigned int key_size;
1203 size_t signature_size;
1204 unsigned char* signature;
1205 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1206
1207 int N = 1 << ftr->N_factor;
1208 int r = 1 << ftr->r_factor;
1209 int p = 1 << ftr->p_factor;
1210
1211 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &key_size);
1212 if (!master_key) {
1213 SLOGE("Failed to convert passwd from hex");
1214 return -1;
1215 }
1216
1217 rc = crypto_scrypt(master_key, key_size, salt, SALT_LEN,
1218 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1219 memset(master_key, 0, key_size);
1220 free(master_key);
1221
1222 if (rc) {
1223 SLOGE("scrypt failed");
1224 return -1;
1225 }
1226
Shawn Willdene17a9c42014-09-08 13:04:08 -06001227 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1228 &signature, &signature_size)) {
1229 SLOGE("Signing failed");
1230 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001231 }
1232
1233 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1234 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1235 free(signature);
1236
1237 if (rc) {
1238 SLOGE("scrypt failed");
1239 return -1;
1240 }
1241
1242 return 0;
1243}
1244
1245static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1246 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001247 unsigned char *encrypted_master_key,
1248 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001249{
1250 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1251 EVP_CIPHER_CTX e_ctx;
1252 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001253 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001254
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001255 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001256 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001257
1258 switch (crypt_ftr->kdf_type) {
1259 case KDF_SCRYPT_KEYMASTER:
1260 if (keymaster_create_key(crypt_ftr)) {
1261 SLOGE("keymaster_create_key failed");
1262 return -1;
1263 }
1264
1265 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1266 SLOGE("scrypt failed");
1267 return -1;
1268 }
1269 break;
1270
1271 case KDF_SCRYPT:
1272 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1273 SLOGE("scrypt failed");
1274 return -1;
1275 }
1276 break;
1277
1278 default:
1279 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001280 return -1;
1281 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001282
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001283 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001284 EVP_CIPHER_CTX_init(&e_ctx);
1285 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001286 SLOGE("EVP_EncryptInit failed\n");
1287 return -1;
1288 }
1289 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001290
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001291 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001292 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
1293 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001294 SLOGE("EVP_EncryptUpdate failed\n");
1295 return -1;
1296 }
Adam Langley889c4f12014-09-03 14:23:13 -07001297 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001298 SLOGE("EVP_EncryptFinal failed\n");
1299 return -1;
1300 }
1301
1302 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1303 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1304 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001305 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001306
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001307 /* Store the scrypt of the intermediate key, so we can validate if it's a
1308 password error or mount error when things go wrong.
1309 Note there's no need to check for errors, since if this is incorrect, we
1310 simply won't wipe userdata, which is the correct default behavior
1311 */
1312 int N = 1 << crypt_ftr->N_factor;
1313 int r = 1 << crypt_ftr->r_factor;
1314 int p = 1 << crypt_ftr->p_factor;
1315
1316 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1317 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1318 crypt_ftr->scrypted_intermediate_key,
1319 sizeof(crypt_ftr->scrypted_intermediate_key));
1320
1321 if (rc) {
1322 SLOGE("encrypt_master_key: crypto_scrypt failed");
1323 }
1324
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001325 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001326}
1327
JP Abgrall7bdfa522013-11-15 13:42:56 -08001328static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001329 unsigned char *encrypted_master_key,
1330 unsigned char *decrypted_master_key,
1331 kdf_func kdf, void *kdf_params,
1332 unsigned char** intermediate_key,
1333 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001334{
1335 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 -08001336 EVP_CIPHER_CTX d_ctx;
1337 int decrypted_len, final_len;
1338
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001339 /* Turn the password into an intermediate key and IV that can decrypt the
1340 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001341 if (kdf(passwd, salt, ikey, kdf_params)) {
1342 SLOGE("kdf failed");
1343 return -1;
1344 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001345
1346 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001347 EVP_CIPHER_CTX_init(&d_ctx);
1348 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001349 return -1;
1350 }
1351 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1352 /* Decrypt the master key */
1353 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1354 encrypted_master_key, KEY_LEN_BYTES)) {
1355 return -1;
1356 }
Adam Langley889c4f12014-09-03 14:23:13 -07001357 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001358 return -1;
1359 }
1360
1361 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1362 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001363 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001364
1365 /* Copy intermediate key if needed by params */
1366 if (intermediate_key && intermediate_key_size) {
1367 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1368 if (intermediate_key) {
1369 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1370 *intermediate_key_size = KEY_LEN_BYTES;
1371 }
1372 }
1373
1374 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001375}
1376
Kenny Rootc4c70f12013-06-14 12:11:38 -07001377static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001378{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001379 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001380 *kdf = scrypt_keymaster;
1381 *kdf_params = ftr;
1382 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001383 *kdf = scrypt;
1384 *kdf_params = ftr;
1385 } else {
1386 *kdf = pbkdf2;
1387 *kdf_params = NULL;
1388 }
1389}
1390
JP Abgrall7bdfa522013-11-15 13:42:56 -08001391static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001392 struct crypt_mnt_ftr *crypt_ftr,
1393 unsigned char** intermediate_key,
1394 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001395{
1396 kdf_func kdf;
1397 void *kdf_params;
1398 int ret;
1399
1400 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001401 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1402 decrypted_master_key, kdf, kdf_params,
1403 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001404 if (ret != 0) {
1405 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001406 }
1407
1408 return ret;
1409}
1410
1411static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1412 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001413 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001414 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001415
1416 /* Get some random bits for a key */
1417 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001418 read(fd, key_buf, sizeof(key_buf));
1419 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001420 close(fd);
1421
1422 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001423 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001424}
1425
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001426static int wait_and_unmount(char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001427{
Greg Hackmann955653e2014-09-24 14:55:20 -07001428 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001429#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001430
1431 /* Now umount the tmpfs filesystem */
1432 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001433 if (umount(mountpoint) == 0) {
1434 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001435 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001436
1437 if (errno == EINVAL) {
1438 /* EINVAL is returned if the directory is not a mountpoint,
1439 * i.e. there is no filesystem mounted there. So just get out.
1440 */
1441 break;
1442 }
1443
1444 err = errno;
1445
1446 /* If allowed, be increasingly aggressive before the last two retries */
1447 if (kill) {
1448 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1449 SLOGW("sending SIGHUP to processes with open files\n");
1450 vold_killProcessesWithOpenFiles(mountpoint, 1);
1451 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1452 SLOGW("sending SIGKILL to processes with open files\n");
1453 vold_killProcessesWithOpenFiles(mountpoint, 2);
1454 }
1455 }
1456
1457 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001458 }
1459
1460 if (i < WAIT_UNMOUNT_COUNT) {
1461 SLOGD("unmounting %s succeeded\n", mountpoint);
1462 rc = 0;
1463 } else {
jessica_yu3f14fe42014-09-22 15:57:40 +08001464 vold_killProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001465 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001466 rc = -1;
1467 }
1468
1469 return rc;
1470}
1471
Ken Sumrallc5872692013-05-14 15:26:31 -07001472#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001473static int prep_data_fs(void)
1474{
1475 int i;
1476
1477 /* Do the prep of the /data filesystem */
1478 property_set("vold.post_fs_data_done", "0");
1479 property_set("vold.decrypt", "trigger_post_fs_data");
1480 SLOGD("Just triggered post_fs_data\n");
1481
Ken Sumrallc5872692013-05-14 15:26:31 -07001482 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001483 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001484 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001485
1486 property_get("vold.post_fs_data_done", p, "0");
1487 if (*p == '1') {
1488 break;
1489 } else {
1490 usleep(250000);
1491 }
1492 }
1493 if (i == DATA_PREP_TIMEOUT) {
1494 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001495 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001496 return -1;
1497 } else {
1498 SLOGD("post_fs_data done\n");
1499 return 0;
1500 }
1501}
1502
Paul Lawrence74f29f12014-08-28 15:54:10 -07001503static void cryptfs_set_corrupt()
1504{
1505 // Mark the footer as bad
1506 struct crypt_mnt_ftr crypt_ftr;
1507 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1508 SLOGE("Failed to get crypto footer - panic");
1509 return;
1510 }
1511
1512 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1513 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1514 SLOGE("Failed to set crypto footer - panic");
1515 return;
1516 }
1517}
1518
1519static void cryptfs_trigger_restart_min_framework()
1520{
1521 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1522 SLOGE("Failed to mount tmpfs on data - panic");
1523 return;
1524 }
1525
1526 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1527 SLOGE("Failed to trigger post fs data - panic");
1528 return;
1529 }
1530
1531 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1532 SLOGE("Failed to trigger restart min framework - panic");
1533 return;
1534 }
1535}
1536
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001537/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001538static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001539{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001540 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001541 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001542 static int restart_successful = 0;
1543
1544 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001545 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001546 SLOGE("Encrypted filesystem not validated, aborting");
1547 return -1;
1548 }
1549
1550 if (restart_successful) {
1551 SLOGE("System already restarted with encrypted disk, aborting");
1552 return -1;
1553 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001554
Paul Lawrencef4faa572014-01-29 13:31:03 -08001555 if (restart_main) {
1556 /* Here is where we shut down the framework. The init scripts
1557 * start all services in one of three classes: core, main or late_start.
1558 * On boot, we start core and main. Now, we stop main, but not core,
1559 * as core includes vold and a few other really important things that
1560 * we need to keep running. Once main has stopped, we should be able
1561 * to umount the tmpfs /data, then mount the encrypted /data.
1562 * We then restart the class main, and also the class late_start.
1563 * At the moment, I've only put a few things in late_start that I know
1564 * are not needed to bring up the framework, and that also cause problems
1565 * with unmounting the tmpfs /data, but I hope to add add more services
1566 * to the late_start class as we optimize this to decrease the delay
1567 * till the user is asked for the password to the filesystem.
1568 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001569
Paul Lawrencef4faa572014-01-29 13:31:03 -08001570 /* The init files are setup to stop the class main when vold.decrypt is
1571 * set to trigger_reset_main.
1572 */
1573 property_set("vold.decrypt", "trigger_reset_main");
1574 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001575
Paul Lawrencef4faa572014-01-29 13:31:03 -08001576 /* Ugh, shutting down the framework is not synchronous, so until it
1577 * can be fixed, this horrible hack will wait a moment for it all to
1578 * shut down before proceeding. Without it, some devices cannot
1579 * restart the graphics services.
1580 */
1581 sleep(2);
1582 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001583
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001584 /* Now that the framework is shutdown, we should be able to umount()
1585 * the tmpfs filesystem, and mount the real one.
1586 */
1587
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001588 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1589 if (strlen(crypto_blkdev) == 0) {
1590 SLOGE("fs_crypto_blkdev not set\n");
1591 return -1;
1592 }
1593
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001594 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001595 /* If ro.crypto.readonly is set to 1, mount the decrypted
1596 * filesystem readonly. This is used when /data is mounted by
1597 * recovery mode.
1598 */
1599 char ro_prop[PROPERTY_VALUE_MAX];
1600 property_get("ro.crypto.readonly", ro_prop, "");
1601 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1602 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1603 rec->flags |= MS_RDONLY;
1604 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001605
Ken Sumralle5032c42012-04-01 23:58:44 -07001606 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001607 int retries = RETRY_MOUNT_ATTEMPTS;
1608 int mount_rc;
1609 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1610 crypto_blkdev, 0))
1611 != 0) {
1612 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1613 /* TODO: invoke something similar to
1614 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1615 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1616 SLOGI("Failed to mount %s because it is busy - waiting",
1617 crypto_blkdev);
1618 if (--retries) {
1619 sleep(RETRY_MOUNT_DELAY_SECONDS);
1620 } else {
1621 /* Let's hope that a reboot clears away whatever is keeping
1622 the mount busy */
1623 cryptfs_reboot(reboot);
1624 }
1625 } else {
1626 SLOGE("Failed to mount decrypted data");
1627 cryptfs_set_corrupt();
1628 cryptfs_trigger_restart_min_framework();
1629 SLOGI("Started framework to offer wipe");
1630 return -1;
1631 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001632 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001633
Ken Sumralle5032c42012-04-01 23:58:44 -07001634 property_set("vold.decrypt", "trigger_load_persist_props");
1635 /* Create necessary paths on /data */
1636 if (prep_data_fs()) {
1637 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001638 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001639
1640 /* startup service classes main and late_start */
1641 property_set("vold.decrypt", "trigger_restart_framework");
1642 SLOGD("Just triggered restart_framework\n");
1643
1644 /* Give it a few moments to get started */
1645 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001646 }
1647
Ken Sumrall0cc16632011-01-18 20:32:26 -08001648 if (rc == 0) {
1649 restart_successful = 1;
1650 }
1651
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001652 return rc;
1653}
1654
Paul Lawrencef4faa572014-01-29 13:31:03 -08001655int cryptfs_restart(void)
1656{
1657 /* Call internal implementation forcing a restart of main service group */
1658 return cryptfs_restart_internal(1);
1659}
1660
Mark Salyzyn3e971272014-01-21 13:27:04 -08001661static int do_crypto_complete(char *mount_point UNUSED)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001662{
1663 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001664 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001665 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001666
1667 property_get("ro.crypto.state", encrypted_state, "");
1668 if (strcmp(encrypted_state, "encrypted") ) {
1669 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001670 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001671 }
1672
Ken Sumrall160b4d62013-04-22 12:15:39 -07001673 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001674 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001675
Ken Sumralle1a45852011-12-14 21:24:27 -08001676 /*
1677 * Only report this error if key_loc is a file and it exists.
1678 * If the device was never encrypted, and /data is not mountable for
1679 * some reason, returning 1 should prevent the UI from presenting the
1680 * a "enter password" screen, or worse, a "press button to wipe the
1681 * device" screen.
1682 */
1683 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1684 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001685 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001686 } else {
1687 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001688 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001689 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001690 }
1691
Paul Lawrence74f29f12014-08-28 15:54:10 -07001692 // Test for possible error flags
1693 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1694 SLOGE("Encryption process is partway completed\n");
1695 return CRYPTO_COMPLETE_PARTIAL;
1696 }
1697
1698 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1699 SLOGE("Encryption process was interrupted but cannot continue\n");
1700 return CRYPTO_COMPLETE_INCONSISTENT;
1701 }
1702
1703 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1704 SLOGE("Encryption is successful but data is corrupt\n");
1705 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001706 }
1707
1708 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001709 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001710}
1711
Paul Lawrencef4faa572014-01-29 13:31:03 -08001712static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1713 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001714{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001715 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001716 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001717 char crypto_blkdev[MAXPATHLEN];
1718 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001719 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001720 unsigned int orig_failed_decrypt_count;
1721 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001722 int use_keymaster = 0;
1723 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001724 unsigned char* intermediate_key = 0;
1725 size_t intermediate_key_size = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001726
Paul Lawrencef4faa572014-01-29 13:31:03 -08001727 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1728 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001729
Paul Lawrencef4faa572014-01-29 13:31:03 -08001730 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001731 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1732 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001733 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001734 rc = -1;
1735 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001736 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001737 }
1738
Paul Lawrencef4faa572014-01-29 13:31:03 -08001739 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1740
Ajay Dudani87701e22014-09-17 21:02:52 -07001741#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001742 if (!strcmp((char *)crypt_ftr->crypto_type_name, "aes-xts")) {
1743 if(!set_hw_device_encryption_key(passwd, (char*) crypt_ftr->crypto_type_name)) {
1744 SLOGE("Hardware encryption key does not match");
1745 }
Ajay Dudani87701e22014-09-17 21:02:52 -07001746 }
1747#endif
1748
Paul Lawrence74f29f12014-08-28 15:54:10 -07001749 // Create crypto block device - all (non fatal) code paths
1750 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001751 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1752 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001753 SLOGE("Error creating decrypted block device\n");
1754 rc = -1;
1755 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001756 }
1757
Paul Lawrence74f29f12014-08-28 15:54:10 -07001758 /* Work out if the problem is the password or the data */
1759 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1760 scrypted_intermediate_key)];
1761 int N = 1 << crypt_ftr->N_factor;
1762 int r = 1 << crypt_ftr->r_factor;
1763 int p = 1 << crypt_ftr->p_factor;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001764
Paul Lawrence74f29f12014-08-28 15:54:10 -07001765 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1766 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1767 N, r, p, scrypted_intermediate_key,
1768 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001769
Paul Lawrence74f29f12014-08-28 15:54:10 -07001770 // Does the key match the crypto footer?
1771 if (rc == 0 && memcmp(scrypted_intermediate_key,
1772 crypt_ftr->scrypted_intermediate_key,
1773 sizeof(scrypted_intermediate_key)) == 0) {
1774 SLOGI("Password matches");
1775 rc = 0;
1776 } else {
1777 /* Try mounting the file system anyway, just in case the problem's with
1778 * the footer, not the key. */
1779 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1780 mkdir(tmp_mount_point, 0755);
1781 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1782 SLOGE("Error temp mounting decrypted block device\n");
1783 delete_crypto_blk_dev(label);
1784
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001785 rc = ++crypt_ftr->failed_decrypt_count;
1786 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001787 } else {
1788 /* Success! */
1789 SLOGI("Password did not match but decrypted drive mounted - continue");
1790 umount(tmp_mount_point);
1791 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001792 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001793 }
1794
1795 if (rc == 0) {
1796 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001797 if (orig_failed_decrypt_count != 0) {
1798 put_crypt_ftr_and_key(crypt_ftr);
1799 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001800
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001801 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001802 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001803 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001804
1805 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001806 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001807 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001808 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001809 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001810 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001811 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001812
Paul Lawrence74f29f12014-08-28 15:54:10 -07001813 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001814 use_keymaster = keymaster_check_compatibility();
1815 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001816 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001817 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1818 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1819 upgrade = 1;
1820 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001821 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001822 upgrade = 1;
1823 }
1824
1825 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001826 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1827 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001828 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001829 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001830 }
1831 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001832
1833 // Do not fail even if upgrade failed - machine is bootable
1834 // Note that if this code is ever hit, there is a *serious* problem
1835 // since KDFs should never fail. You *must* fix the kdf before
1836 // proceeding!
1837 if (rc) {
1838 SLOGW("Upgrade failed with error %d,"
1839 " but continuing with previous state",
1840 rc);
1841 rc = 0;
1842 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001843 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001844 }
1845
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001846 errout:
1847 if (intermediate_key) {
1848 memset(intermediate_key, 0, intermediate_key_size);
1849 free(intermediate_key);
1850 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001851 return rc;
1852}
1853
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001854/* Called by vold when it wants to undo the crypto mapping of a volume it
1855 * manages. This is usually in response to a factory reset, when we want
1856 * to undo the crypto mapping so the volume is formatted in the clear.
1857 */
1858int cryptfs_revert_volume(const char *label)
1859{
1860 return delete_crypto_blk_dev((char *)label);
1861}
1862
Ken Sumrall29d8da82011-05-18 17:20:07 -07001863/*
1864 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1865 * Setup a dm-crypt mapping, use the saved master key from
1866 * setting up the /data mapping, and return the new device path.
1867 */
1868int cryptfs_setup_volume(const char *label, int major, int minor,
1869 char *crypto_sys_path, unsigned int max_path,
1870 int *new_major, int *new_minor)
1871{
1872 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1873 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001874 struct stat statbuf;
Tim Murray8439dc92014-12-15 11:56:11 -08001875 unsigned int nr_sec;
1876 int fd;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001877
1878 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1879
Ken Sumrall160b4d62013-04-22 12:15:39 -07001880 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001881
1882 /* Update the fs_size field to be the size of the volume */
1883 fd = open(real_blkdev, O_RDONLY);
1884 nr_sec = get_blkdev_size(fd);
1885 close(fd);
1886 if (nr_sec == 0) {
1887 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1888 return -1;
1889 }
1890
1891 sd_crypt_ftr.fs_size = nr_sec;
1892 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1893 crypto_blkdev, label);
1894
JP Abgrall3334c6a2014-10-10 15:52:11 -07001895 if (stat(crypto_blkdev, &statbuf) < 0) {
1896 SLOGE("Error get stat for crypto_blkdev %s. err=%d(%s)\n",
1897 crypto_blkdev, errno, strerror(errno));
1898 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07001899 *new_major = MAJOR(statbuf.st_rdev);
1900 *new_minor = MINOR(statbuf.st_rdev);
1901
1902 /* Create path to sys entry for this block device */
1903 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1904
1905 return 0;
1906}
1907
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001908int cryptfs_crypto_complete(void)
1909{
1910 return do_crypto_complete("/data");
1911}
1912
Paul Lawrencef4faa572014-01-29 13:31:03 -08001913int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1914{
1915 char encrypted_state[PROPERTY_VALUE_MAX];
1916 property_get("ro.crypto.state", encrypted_state, "");
1917 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1918 SLOGE("encrypted fs already validated or not running with encryption,"
1919 " aborting");
1920 return -1;
1921 }
1922
1923 if (get_crypt_ftr_and_key(crypt_ftr)) {
1924 SLOGE("Error getting crypt footer and key");
1925 return -1;
1926 }
1927
1928 return 0;
1929}
1930
Paul Lawrencefc615042014-10-04 15:32:29 -07001931/*
1932 * TODO - transition patterns to new format in calling code
1933 * and remove this vile hack, and the use of hex in
1934 * the password passing code.
1935 *
1936 * Patterns are passed in zero based (i.e. the top left dot
1937 * is represented by zero, the top middle one etc), but we want
1938 * to store them '1' based.
1939 * This is to allow us to migrate the calling code to use this
1940 * convention. It also solves a nasty problem whereby scrypt ignores
1941 * trailing zeros, so patterns ending at the top left could be
1942 * truncated, and similarly, you could add the top left to any
1943 * pattern and still match.
1944 * adjust_passwd is a hack function that returns the alternate representation
1945 * if the password appears to be a pattern (hex numbers all less than 09)
1946 * If it succeeds we need to try both, and in particular try the alternate
1947 * first. If the original matches, then we need to update the footer
1948 * with the alternate.
1949 * All code that accepts passwords must adjust them first. Since
1950 * cryptfs_check_passwd is always the first function called after a migration
1951 * (and indeed on any boot) we only need to do the double try in this
1952 * function.
1953 */
1954char* adjust_passwd(const char* passwd)
1955{
1956 size_t index, length;
1957
1958 if (!passwd) {
1959 return 0;
1960 }
1961
1962 // Check even length. Hex encoded passwords are always
1963 // an even length, since each character encodes to two characters.
1964 length = strlen(passwd);
1965 if (length % 2) {
1966 SLOGW("Password not correctly hex encoded.");
1967 return 0;
1968 }
1969
1970 // Check password is old-style pattern - a collection of hex
1971 // encoded bytes less than 9 (00 through 08)
1972 for (index = 0; index < length; index +=2) {
1973 if (passwd[index] != '0'
1974 || passwd[index + 1] < '0' || passwd[index + 1] > '8') {
1975 return 0;
1976 }
1977 }
1978
1979 // Allocate room for adjusted passwd and null terminate
1980 char* adjusted = malloc(length + 1);
1981 adjusted[length] = 0;
1982
1983 // Add 0x31 ('1') to each character
1984 for (index = 0; index < length; index += 2) {
1985 // output is 31 through 39 so set first byte to three, second to src + 1
1986 adjusted[index] = '3';
1987 adjusted[index + 1] = passwd[index + 1] + 1;
1988 }
1989
1990 return adjusted;
1991}
1992
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001993int cryptfs_check_passwd(char *passwd)
1994{
Paul Lawrencef4faa572014-01-29 13:31:03 -08001995 struct crypt_mnt_ftr crypt_ftr;
1996 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001997
Paul Lawrencef4faa572014-01-29 13:31:03 -08001998 rc = check_unmounted_and_get_ftr(&crypt_ftr);
1999 if (rc)
2000 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002001
Paul Lawrencefc615042014-10-04 15:32:29 -07002002 char* adjusted_passwd = adjust_passwd(passwd);
2003 if (adjusted_passwd) {
2004 int failed_decrypt_count = crypt_ftr.failed_decrypt_count;
2005 rc = test_mount_encrypted_fs(&crypt_ftr, adjusted_passwd,
2006 DATA_MNT_POINT, "userdata");
2007
2008 // Maybe the original one still works?
2009 if (rc) {
2010 // Don't double count this failure
2011 crypt_ftr.failed_decrypt_count = failed_decrypt_count;
2012 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
2013 DATA_MNT_POINT, "userdata");
2014 if (!rc) {
2015 // cryptfs_changepw also adjusts so pass original
2016 // Note that adjust_passwd only recognises patterns
2017 // so we can safely use CRYPT_TYPE_PATTERN
2018 SLOGI("Updating pattern to new format");
2019 cryptfs_changepw(CRYPT_TYPE_PATTERN, passwd);
2020 }
2021 }
2022 free(adjusted_passwd);
2023 } else {
2024 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
2025 DATA_MNT_POINT, "userdata");
2026 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002027
2028 if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002029 cryptfs_clear_password();
2030 password = strdup(passwd);
2031 struct timespec now;
2032 clock_gettime(CLOCK_BOOTTIME, &now);
2033 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002034 }
2035
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002036 return rc;
2037}
2038
Ken Sumrall3ad90722011-10-04 20:38:29 -07002039int cryptfs_verify_passwd(char *passwd)
2040{
2041 struct crypt_mnt_ftr crypt_ftr;
2042 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002043 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002044 char encrypted_state[PROPERTY_VALUE_MAX];
2045 int rc;
2046
2047 property_get("ro.crypto.state", encrypted_state, "");
2048 if (strcmp(encrypted_state, "encrypted") ) {
2049 SLOGE("device not encrypted, aborting");
2050 return -2;
2051 }
2052
2053 if (!master_key_saved) {
2054 SLOGE("encrypted fs not yet mounted, aborting");
2055 return -1;
2056 }
2057
2058 if (!saved_mount_point) {
2059 SLOGE("encrypted fs failed to save mount point, aborting");
2060 return -1;
2061 }
2062
Ken Sumrall160b4d62013-04-22 12:15:39 -07002063 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002064 SLOGE("Error getting crypt footer and key\n");
2065 return -1;
2066 }
2067
2068 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2069 /* If the device has no password, then just say the password is valid */
2070 rc = 0;
2071 } else {
Paul Lawrencefc615042014-10-04 15:32:29 -07002072 char* adjusted_passwd = adjust_passwd(passwd);
2073 if (adjusted_passwd) {
2074 passwd = adjusted_passwd;
2075 }
2076
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002077 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002078 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2079 /* They match, the password is correct */
2080 rc = 0;
2081 } else {
2082 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2083 sleep(1);
2084 rc = 1;
2085 }
Paul Lawrencefc615042014-10-04 15:32:29 -07002086
2087 free(adjusted_passwd);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002088 }
2089
2090 return rc;
2091}
2092
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002093/* Initialize a crypt_mnt_ftr structure. The keysize is
2094 * defaulted to 16 bytes, and the filesystem size to 0.
2095 * Presumably, at a minimum, the caller will update the
2096 * filesystem size and crypto_type_name after calling this function.
2097 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002098static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002099{
Ken Sumrall160b4d62013-04-22 12:15:39 -07002100 off64_t off;
2101
2102 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002103 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002104 ftr->major_version = CURRENT_MAJOR_VERSION;
2105 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002106 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06002107 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002108
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002109 switch (keymaster_check_compatibility()) {
2110 case 1:
2111 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2112 break;
2113
2114 case 0:
2115 ftr->kdf_type = KDF_SCRYPT;
2116 break;
2117
2118 default:
2119 SLOGE("keymaster_check_compatibility failed");
2120 return -1;
2121 }
2122
Kenny Rootc4c70f12013-06-14 12:11:38 -07002123 get_device_scrypt_params(ftr);
2124
Ken Sumrall160b4d62013-04-22 12:15:39 -07002125 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2126 if (get_crypt_ftr_info(NULL, &off) == 0) {
2127 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
2128 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
2129 ftr->persist_data_size;
2130 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002131
2132 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002133}
2134
Ken Sumrall29d8da82011-05-18 17:20:07 -07002135static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002136{
Ken Sumralle550f782013-08-20 13:48:23 -07002137 const char *args[10];
2138 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
2139 int num_args;
2140 int status;
2141 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002142 int rc = -1;
2143
Ken Sumrall29d8da82011-05-18 17:20:07 -07002144 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07002145 args[0] = "/system/bin/make_ext4fs";
2146 args[1] = "-a";
2147 args[2] = "/data";
2148 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07002149 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07002150 args[4] = size_str;
2151 args[5] = crypto_blkdev;
2152 num_args = 6;
2153 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
2154 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07002155 } else if (type == F2FS_FS) {
2156 args[0] = "/system/bin/mkfs.f2fs";
2157 args[1] = "-t";
2158 args[2] = "-d1";
2159 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07002160 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07002161 args[4] = size_str;
2162 num_args = 5;
2163 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
2164 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002165 } else {
2166 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
2167 return -1;
2168 }
2169
Ken Sumralle550f782013-08-20 13:48:23 -07002170 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
2171
2172 if (tmp != 0) {
2173 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002174 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07002175 if (WIFEXITED(status)) {
2176 if (WEXITSTATUS(status)) {
2177 SLOGE("Error creating filesystem on %s, exit status %d ",
2178 crypto_blkdev, WEXITSTATUS(status));
2179 } else {
2180 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
2181 rc = 0;
2182 }
2183 } else {
2184 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
2185 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002186 }
2187
2188 return rc;
2189}
2190
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002191#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08002192#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
2193#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002194
2195/* aligned 32K writes tends to make flash happy.
2196 * SD card association recommends it.
2197 */
Ajay Dudani87701e22014-09-17 21:02:52 -07002198#ifndef CONFIG_HW_DISK_ENCRYPTION
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002199#define BLOCKS_AT_A_TIME 8
Ajay Dudani87701e22014-09-17 21:02:52 -07002200#else
2201#define BLOCKS_AT_A_TIME 1024
2202#endif
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002203
2204struct encryptGroupsData
2205{
2206 int realfd;
2207 int cryptofd;
2208 off64_t numblocks;
2209 off64_t one_pct, cur_pct, new_pct;
2210 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002211 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002212 char* real_blkdev, * crypto_blkdev;
2213 int count;
2214 off64_t offset;
2215 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08002216 off64_t last_written_sector;
2217 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002218 time_t time_started;
2219 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002220};
2221
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002222static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002223{
2224 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002225
2226 if (is_used) {
2227 data->used_blocks_already_done++;
2228 }
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002229 if (data->tot_used_blocks) {
2230 data->new_pct = data->used_blocks_already_done / data->one_pct;
2231 } else {
2232 data->new_pct = data->blocks_already_done / data->one_pct;
2233 }
2234
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002235 if (data->new_pct > data->cur_pct) {
2236 char buf[8];
2237 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07002238 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002239 property_set("vold.encrypt_progress", buf);
2240 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002241
2242 if (data->cur_pct >= 5) {
Paul Lawrence9c58a872014-09-30 09:12:51 -07002243 struct timespec time_now;
2244 if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
2245 SLOGW("Error getting time");
2246 } else {
2247 double elapsed_time = difftime(time_now.tv_sec, data->time_started);
2248 off64_t remaining_blocks = data->tot_used_blocks
2249 - data->used_blocks_already_done;
2250 int remaining_time = (int)(elapsed_time * remaining_blocks
2251 / data->used_blocks_already_done);
Paul Lawrence71577502014-08-13 14:55:55 -07002252
Paul Lawrence9c58a872014-09-30 09:12:51 -07002253 // Change time only if not yet set, lower, or a lot higher for
2254 // best user experience
2255 if (data->remaining_time == -1
2256 || remaining_time < data->remaining_time
2257 || remaining_time > data->remaining_time + 60) {
2258 char buf[8];
2259 snprintf(buf, sizeof(buf), "%d", remaining_time);
2260 property_set("vold.encrypt_time_remaining", buf);
2261 data->remaining_time = remaining_time;
2262 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002263 }
2264 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002265}
2266
Paul Lawrence3846be12014-09-22 11:33:54 -07002267static void log_progress(struct encryptGroupsData const* data, bool completed)
2268{
2269 // Precondition - if completed data = 0 else data != 0
2270
2271 // Track progress so we can skip logging blocks
2272 static off64_t offset = -1;
2273
2274 // Need to close existing 'Encrypting from' log?
2275 if (completed || (offset != -1 && data->offset != offset)) {
2276 SLOGI("Encrypted to sector %" PRId64,
2277 offset / info.block_size * CRYPT_SECTOR_SIZE);
2278 offset = -1;
2279 }
2280
2281 // Need to start new 'Encrypting from' log?
2282 if (!completed && offset != data->offset) {
2283 SLOGI("Encrypting from sector %" PRId64,
2284 data->offset / info.block_size * CRYPT_SECTOR_SIZE);
2285 }
2286
2287 // Update offset
2288 if (!completed) {
2289 offset = data->offset + (off64_t)data->count * info.block_size;
2290 }
2291}
2292
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002293static int flush_outstanding_data(struct encryptGroupsData* data)
2294{
2295 if (data->count == 0) {
2296 return 0;
2297 }
2298
Elliott Hughes231bdba2014-06-25 18:36:19 -07002299 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002300
2301 if (pread64(data->realfd, data->buffer,
2302 info.block_size * data->count, data->offset)
2303 <= 0) {
2304 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2305 data->real_blkdev);
2306 return -1;
2307 }
2308
2309 if (pwrite64(data->cryptofd, data->buffer,
2310 info.block_size * data->count, data->offset)
2311 <= 0) {
2312 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2313 data->crypto_blkdev);
2314 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002315 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002316 log_progress(data, false);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002317 }
2318
2319 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002320 data->last_written_sector = (data->offset + data->count)
2321 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002322 return 0;
2323}
2324
2325static int encrypt_groups(struct encryptGroupsData* data)
2326{
2327 unsigned int i;
2328 u8 *block_bitmap = 0;
2329 unsigned int block;
2330 off64_t ret;
2331 int rc = -1;
2332
2333 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
2334 if (!data->buffer) {
2335 SLOGE("Failed to allocate crypto buffer");
2336 goto errout;
2337 }
2338
2339 block_bitmap = malloc(info.block_size);
2340 if (!block_bitmap) {
2341 SLOGE("failed to allocate block bitmap");
2342 goto errout;
2343 }
2344
2345 for (i = 0; i < aux_info.groups; ++i) {
2346 SLOGI("Encrypting group %d", i);
2347
2348 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2349 u32 block_count = min(info.blocks_per_group,
2350 aux_info.len_blocks - first_block);
2351
2352 off64_t offset = (u64)info.block_size
2353 * aux_info.bg_desc[i].bg_block_bitmap;
2354
2355 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2356 if (ret != (int)info.block_size) {
2357 SLOGE("failed to read all of block group bitmap %d", i);
2358 goto errout;
2359 }
2360
2361 offset = (u64)info.block_size * first_block;
2362
2363 data->count = 0;
2364
2365 for (block = 0; block < block_count; block++) {
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002366 int used = bitmap_get_bit(block_bitmap, block);
2367 update_progress(data, used);
2368 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002369 if (data->count == 0) {
2370 data->offset = offset;
2371 }
2372 data->count++;
2373 } else {
2374 if (flush_outstanding_data(data)) {
2375 goto errout;
2376 }
2377 }
2378
2379 offset += info.block_size;
2380
2381 /* Write data if we are aligned or buffer size reached */
2382 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2383 || data->count == BLOCKS_AT_A_TIME) {
2384 if (flush_outstanding_data(data)) {
2385 goto errout;
2386 }
2387 }
Paul Lawrence87999172014-02-20 12:21:31 -08002388
Paul Lawrence73d7a022014-06-09 14:10:09 -07002389 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002390 SLOGE("Stopping encryption due to low battery");
2391 rc = 0;
2392 goto errout;
2393 }
2394
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002395 }
2396 if (flush_outstanding_data(data)) {
2397 goto errout;
2398 }
2399 }
2400
Paul Lawrence87999172014-02-20 12:21:31 -08002401 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002402 rc = 0;
2403
2404errout:
Paul Lawrence3846be12014-09-22 11:33:54 -07002405 log_progress(0, true);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002406 free(data->buffer);
2407 free(block_bitmap);
2408 return rc;
2409}
2410
2411static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2412 char *real_blkdev,
2413 off64_t size,
2414 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002415 off64_t tot_size,
2416 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002417{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002418 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002419 struct encryptGroupsData data;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002420 int rc; // Can't initialize without causing warning -Wclobbered
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002421
Paul Lawrence87999172014-02-20 12:21:31 -08002422 if (previously_encrypted_upto > *size_already_done) {
2423 SLOGD("Not fast encrypting since resuming part way through");
2424 return -1;
2425 }
2426
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002427 memset(&data, 0, sizeof(data));
2428 data.real_blkdev = real_blkdev;
2429 data.crypto_blkdev = crypto_blkdev;
2430
2431 if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002432 SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
2433 real_blkdev, errno, strerror(errno));
Paul Lawrence74f29f12014-08-28 15:54:10 -07002434 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002435 goto errout;
2436 }
2437
2438 if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002439 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
JP Abgrall3334c6a2014-10-10 15:52:11 -07002440 crypto_blkdev, errno, strerror(errno));
JP Abgrall7fc1de82014-10-10 18:43:41 -07002441 rc = ENABLE_INPLACE_ERR_DEV;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002442 goto errout;
2443 }
2444
2445 if (setjmp(setjmp_env)) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002446 SLOGE("Reading ext4 extent caused an exception\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002447 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002448 goto errout;
2449 }
2450
2451 if (read_ext(data.realfd, 0) != 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002452 SLOGE("Failed to read ext4 extent\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002453 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002454 goto errout;
2455 }
2456
2457 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2458 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2459 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2460
JP Abgrall7fc1de82014-10-10 18:43:41 -07002461 SLOGI("Encrypting ext4 filesystem in place...");
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002462
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002463 data.tot_used_blocks = data.numblocks;
2464 for (i = 0; i < aux_info.groups; ++i) {
2465 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2466 }
2467
2468 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002469 data.cur_pct = 0;
Paul Lawrence9c58a872014-09-30 09:12:51 -07002470
2471 struct timespec time_started = {0};
2472 if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
2473 SLOGW("Error getting time at start");
2474 // Note - continue anyway - we'll run with 0
2475 }
2476 data.time_started = time_started.tv_sec;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002477 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002478
2479 rc = encrypt_groups(&data);
2480 if (rc) {
2481 SLOGE("Error encrypting groups");
2482 goto errout;
2483 }
2484
Paul Lawrence87999172014-02-20 12:21:31 -08002485 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002486 rc = 0;
2487
2488errout:
2489 close(data.realfd);
2490 close(data.cryptofd);
2491
2492 return rc;
2493}
2494
Paul Lawrence3846be12014-09-22 11:33:54 -07002495static void log_progress_f2fs(u64 block, bool completed)
2496{
2497 // Precondition - if completed data = 0 else data != 0
2498
2499 // Track progress so we can skip logging blocks
2500 static u64 last_block = (u64)-1;
2501
2502 // Need to close existing 'Encrypting from' log?
2503 if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
2504 SLOGI("Encrypted to block %" PRId64, last_block);
2505 last_block = -1;
2506 }
2507
2508 // Need to start new 'Encrypting from' log?
2509 if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
2510 SLOGI("Encrypting from block %" PRId64, block);
2511 }
2512
2513 // Update offset
2514 if (!completed) {
2515 last_block = block;
2516 }
2517}
2518
Daniel Rosenberge82df162014-08-15 22:19:23 +00002519static int encrypt_one_block_f2fs(u64 pos, void *data)
2520{
2521 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2522
2523 priv_dat->blocks_already_done = pos - 1;
2524 update_progress(priv_dat, 1);
2525
2526 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2527
2528 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002529 SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002530 return -1;
2531 }
2532
2533 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002534 SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002535 return -1;
2536 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002537 log_progress_f2fs(pos, false);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002538 }
2539
2540 return 0;
2541}
2542
2543static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2544 char *real_blkdev,
2545 off64_t size,
2546 off64_t *size_already_done,
2547 off64_t tot_size,
2548 off64_t previously_encrypted_upto)
2549{
Daniel Rosenberge82df162014-08-15 22:19:23 +00002550 struct encryptGroupsData data;
2551 struct f2fs_info *f2fs_info = NULL;
JP Abgrall7fc1de82014-10-10 18:43:41 -07002552 int rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002553 if (previously_encrypted_upto > *size_already_done) {
2554 SLOGD("Not fast encrypting since resuming part way through");
JP Abgrall7fc1de82014-10-10 18:43:41 -07002555 return ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002556 }
2557 memset(&data, 0, sizeof(data));
2558 data.real_blkdev = real_blkdev;
2559 data.crypto_blkdev = crypto_blkdev;
2560 data.realfd = -1;
2561 data.cryptofd = -1;
2562 if ( (data.realfd = open64(real_blkdev, O_RDWR)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002563 SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
Daniel Rosenberge82df162014-08-15 22:19:23 +00002564 real_blkdev);
2565 goto errout;
2566 }
2567 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002568 SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
JP Abgrall3334c6a2014-10-10 15:52:11 -07002569 crypto_blkdev, errno, strerror(errno));
JP Abgrall7fc1de82014-10-10 18:43:41 -07002570 rc = ENABLE_INPLACE_ERR_DEV;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002571 goto errout;
2572 }
2573
2574 f2fs_info = generate_f2fs_info(data.realfd);
2575 if (!f2fs_info)
2576 goto errout;
2577
2578 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2579 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2580 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2581
2582 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2583
2584 data.one_pct = data.tot_used_blocks / 100;
2585 data.cur_pct = 0;
2586 data.time_started = time(NULL);
2587 data.remaining_time = -1;
2588
2589 data.buffer = malloc(f2fs_info->block_size);
2590 if (!data.buffer) {
2591 SLOGE("Failed to allocate crypto buffer");
2592 goto errout;
2593 }
2594
2595 data.count = 0;
2596
2597 /* Currently, this either runs to completion, or hits a nonrecoverable error */
2598 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2599
2600 if (rc) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002601 SLOGE("Error in running over f2fs blocks");
2602 rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002603 goto errout;
2604 }
2605
2606 *size_already_done += size;
2607 rc = 0;
2608
2609errout:
2610 if (rc)
2611 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2612
Paul Lawrence3846be12014-09-22 11:33:54 -07002613 log_progress_f2fs(0, true);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002614 free(f2fs_info);
2615 free(data.buffer);
2616 close(data.realfd);
2617 close(data.cryptofd);
2618
2619 return rc;
2620}
2621
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002622static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2623 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002624 off64_t tot_size,
2625 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002626{
2627 int realfd, cryptofd;
2628 char *buf[CRYPT_INPLACE_BUFSIZE];
JP Abgrall7fc1de82014-10-10 18:43:41 -07002629 int rc = ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002630 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002631 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002632 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002633
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002634 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
2635 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002636 return ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002637 }
2638
2639 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002640 SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
2641 crypto_blkdev, errno, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002642 close(realfd);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002643 return ENABLE_INPLACE_ERR_DEV;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002644 }
2645
2646 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2647 * The size passed in is the number of 512 byte sectors in the filesystem.
2648 * So compute the number of whole 4K blocks we should read/write,
2649 * and the remainder.
2650 */
2651 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2652 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002653 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2654 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002655
2656 SLOGE("Encrypting filesystem in place...");
2657
Paul Lawrence87999172014-02-20 12:21:31 -08002658 i = previously_encrypted_upto + 1 - *size_already_done;
2659
2660 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2661 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2662 goto errout;
2663 }
2664
2665 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2666 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2667 goto errout;
2668 }
2669
2670 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2671 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2672 SLOGE("Error reading initial sectors from real_blkdev %s for "
2673 "inplace encrypt\n", crypto_blkdev);
2674 goto errout;
2675 }
2676 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2677 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2678 "inplace encrypt\n", crypto_blkdev);
2679 goto errout;
2680 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002681 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002682 }
2683 }
2684
Ken Sumrall29d8da82011-05-18 17:20:07 -07002685 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002686 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002687 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002688 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002689 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002690 if (new_pct > cur_pct) {
2691 char buf[8];
2692
2693 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002694 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002695 property_set("vold.encrypt_progress", buf);
2696 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002697 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002698 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002699 goto errout;
2700 }
2701 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002702 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2703 goto errout;
2704 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002705 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002706 CRYPT_SECTORS_PER_BUFSIZE,
2707 i * CRYPT_SECTORS_PER_BUFSIZE);
2708 }
2709
Paul Lawrence73d7a022014-06-09 14:10:09 -07002710 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002711 SLOGE("Stopping encryption due to low battery");
2712 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2713 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002714 goto errout;
2715 }
2716 }
2717
2718 /* Do any remaining sectors */
2719 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002720 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2721 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002722 goto errout;
2723 }
Paul Lawrence87999172014-02-20 12:21:31 -08002724 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2725 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002726 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002727 } else {
2728 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002729 }
2730 }
2731
Ken Sumrall29d8da82011-05-18 17:20:07 -07002732 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002733 rc = 0;
2734
2735errout:
2736 close(realfd);
2737 close(cryptofd);
2738
2739 return rc;
2740}
2741
JP Abgrall7fc1de82014-10-10 18:43:41 -07002742/* returns on of the ENABLE_INPLACE_* return codes */
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002743static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2744 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002745 off64_t tot_size,
2746 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002747{
JP Abgrall7fc1de82014-10-10 18:43:41 -07002748 int rc_ext4, rc_f2fs, rc_full;
Paul Lawrence87999172014-02-20 12:21:31 -08002749 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002750 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002751 }
2752
2753 if (*size_already_done + size < previously_encrypted_upto) {
2754 *size_already_done += size;
2755 return 0;
2756 }
2757
Daniel Rosenberge82df162014-08-15 22:19:23 +00002758 /* TODO: identify filesystem type.
2759 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2760 * then we will drop down to cryptfs_enable_inplace_f2fs.
2761 * */
JP Abgrall7fc1de82014-10-10 18:43:41 -07002762 if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002763 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002764 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002765 return 0;
2766 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002767 SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002768
JP Abgrall7fc1de82014-10-10 18:43:41 -07002769 if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002770 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002771 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002772 return 0;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002773 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002774 SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002775
JP Abgrall7fc1de82014-10-10 18:43:41 -07002776 rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002777 size, size_already_done, tot_size,
2778 previously_encrypted_upto);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002779 SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
2780
2781 /* Hack for b/17898962, the following is the symptom... */
2782 if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
2783 && rc_f2fs == ENABLE_INPLACE_ERR_DEV
2784 && rc_full == ENABLE_INPLACE_ERR_DEV) {
2785 return ENABLE_INPLACE_ERR_DEV;
2786 }
2787 return rc_full;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002788}
2789
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002790#define CRYPTO_ENABLE_WIPE 1
2791#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002792
2793#define FRAMEWORK_BOOT_WAIT 60
2794
Ken Sumrall29d8da82011-05-18 17:20:07 -07002795static inline int should_encrypt(struct volume_info *volume)
2796{
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002797 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
Ken Sumrall29d8da82011-05-18 17:20:07 -07002798 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
2799}
2800
Paul Lawrence87999172014-02-20 12:21:31 -08002801static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2802{
2803 int fd = open(filename, O_RDONLY);
2804 if (fd == -1) {
2805 SLOGE("Error opening file %s", filename);
2806 return -1;
2807 }
2808
2809 char block[CRYPT_INPLACE_BUFSIZE];
2810 memset(block, 0, sizeof(block));
2811 if (unix_read(fd, block, sizeof(block)) < 0) {
2812 SLOGE("Error reading file %s", filename);
2813 close(fd);
2814 return -1;
2815 }
2816
2817 close(fd);
2818
2819 SHA256_CTX c;
2820 SHA256_Init(&c);
2821 SHA256_Update(&c, block, sizeof(block));
2822 SHA256_Final(buf, &c);
2823
2824 return 0;
2825}
2826
JP Abgrall62c7af32014-06-16 13:01:23 -07002827static int get_fs_type(struct fstab_rec *rec)
2828{
2829 if (!strcmp(rec->fs_type, "ext4")) {
2830 return EXT4_FS;
2831 } else if (!strcmp(rec->fs_type, "f2fs")) {
2832 return F2FS_FS;
2833 } else {
2834 return -1;
2835 }
2836}
2837
Paul Lawrence87999172014-02-20 12:21:31 -08002838static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2839 char *crypto_blkdev, char *real_blkdev,
2840 int previously_encrypted_upto)
2841{
2842 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002843 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002844
Paul Lawrence73d7a022014-06-09 14:10:09 -07002845 if (!is_battery_ok_to_start()) {
2846 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002847 return 0;
2848 }
2849
2850 /* The size of the userdata partition, and add in the vold volumes below */
2851 tot_encryption_size = crypt_ftr->fs_size;
2852
2853 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002854 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2855 int fs_type = get_fs_type(rec);
2856 if (fs_type < 0) {
2857 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2858 return -1;
2859 }
2860 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002861 } else if (how == CRYPTO_ENABLE_INPLACE) {
2862 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2863 crypt_ftr->fs_size, &cur_encryption_done,
2864 tot_encryption_size,
2865 previously_encrypted_upto);
2866
JP Abgrall7fc1de82014-10-10 18:43:41 -07002867 if (rc == ENABLE_INPLACE_ERR_DEV) {
2868 /* Hack for b/17898962 */
2869 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2870 cryptfs_reboot(reboot);
2871 }
2872
Paul Lawrence73d7a022014-06-09 14:10:09 -07002873 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002874 crypt_ftr->encrypted_upto = cur_encryption_done;
2875 }
2876
Paul Lawrence73d7a022014-06-09 14:10:09 -07002877 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002878 /* The inplace routine never actually sets the progress to 100% due
2879 * to the round down nature of integer division, so set it here */
2880 property_set("vold.encrypt_progress", "100");
2881 }
2882 } else {
2883 /* Shouldn't happen */
2884 SLOGE("cryptfs_enable: internal error, unknown option\n");
2885 rc = -1;
2886 }
2887
2888 return rc;
2889}
2890
Paul Lawrence13486032014-02-03 13:28:11 -08002891int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
2892 int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002893{
2894 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002895 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07002896 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002897 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Tim Murray8439dc92014-12-15 11:56:11 -08002898 int rc=-1, fd, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002899 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002900 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002901 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002902 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002903 char key_loc[PROPERTY_VALUE_MAX];
2904 char fuse_sdcard[PROPERTY_VALUE_MAX];
2905 char *sd_mnt_point;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002906 int num_vols;
2907 struct volume_info *vol_list = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002908 off64_t previously_encrypted_upto = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002909
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002910 if (!strcmp(howarg, "wipe")) {
2911 how = CRYPTO_ENABLE_WIPE;
2912 } else if (! strcmp(howarg, "inplace")) {
2913 how = CRYPTO_ENABLE_INPLACE;
2914 } else {
2915 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002916 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002917 }
2918
Paul Lawrence87999172014-02-20 12:21:31 -08002919 /* See if an encryption was underway and interrupted */
2920 if (how == CRYPTO_ENABLE_INPLACE
2921 && get_crypt_ftr_and_key(&crypt_ftr) == 0
2922 && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
2923 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2924 crypt_ftr.encrypted_upto = 0;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002925 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
2926
2927 /* At this point, we are in an inconsistent state. Until we successfully
2928 complete encryption, a reboot will leave us broken. So mark the
2929 encryption failed in case that happens.
2930 On successfully completing encryption, remove this flag */
2931 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2932
2933 put_crypt_ftr_and_key(&crypt_ftr);
Paul Lawrence87999172014-02-20 12:21:31 -08002934 }
2935
2936 property_get("ro.crypto.state", encrypted_state, "");
2937 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2938 SLOGE("Device is already running encrypted, aborting");
2939 goto error_unencrypted;
2940 }
2941
2942 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2943 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002944 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002945
Ken Sumrall3ed82362011-01-28 23:31:16 -08002946 /* Get the size of the real block device */
2947 fd = open(real_blkdev, O_RDONLY);
2948 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
2949 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2950 goto error_unencrypted;
2951 }
2952 close(fd);
2953
2954 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002955 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002956 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002957 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002958 if (fs_size_sec == 0)
2959 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2960
Paul Lawrence87999172014-02-20 12:21:31 -08002961 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002962
2963 if (fs_size_sec > max_fs_size_sec) {
2964 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2965 goto error_unencrypted;
2966 }
2967 }
2968
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002969 /* Get a wakelock as this may take a while, and we don't want the
2970 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2971 * wants to keep the screen on, it can grab a full wakelock.
2972 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002973 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002974 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2975
Jeff Sharkey7382f812012-08-23 14:08:59 -07002976 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07002977 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07002978 if (!sd_mnt_point) {
2979 sd_mnt_point = getenv("EXTERNAL_STORAGE");
2980 }
2981 if (!sd_mnt_point) {
2982 sd_mnt_point = "/mnt/sdcard";
2983 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07002984
Paul Lawrence87999172014-02-20 12:21:31 -08002985 /* TODO
2986 * Currently do not have test devices with multiple encryptable volumes.
2987 * When we acquire some, re-add support.
2988 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002989 num_vols=vold_getNumDirectVolumes();
2990 vol_list = malloc(sizeof(struct volume_info) * num_vols);
2991 vold_getDirectVolumeList(vol_list);
2992
2993 for (i=0; i<num_vols; i++) {
2994 if (should_encrypt(&vol_list[i])) {
Paul Lawrence87999172014-02-20 12:21:31 -08002995 SLOGE("Cannot encrypt if there are multiple encryptable volumes"
2996 "%s\n", vol_list[i].label);
2997 goto error_unencrypted;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002998 }
2999 }
3000
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003001 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003002 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003003 */
3004 property_set("vold.decrypt", "trigger_shutdown_framework");
3005 SLOGD("Just asked init to shut down class main\n");
3006
Ken Sumrall425524d2012-06-14 20:55:28 -07003007 if (vold_unmountAllAsecs()) {
3008 /* Just report the error. If any are left mounted,
3009 * umounting /data below will fail and handle the error.
3010 */
3011 SLOGE("Error unmounting internal asecs");
3012 }
3013
Ken Sumrall29d8da82011-05-18 17:20:07 -07003014 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
3015 if (!strcmp(fuse_sdcard, "true")) {
3016 /* This is a device using the fuse layer to emulate the sdcard semantics
3017 * on top of the userdata partition. vold does not manage it, it is managed
3018 * by the sdcard service. The sdcard service was killed by the property trigger
3019 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
3020 * unlike the case for vold managed devices above.
3021 */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07003022 if (wait_and_unmount(sd_mnt_point, false)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07003023 goto error_shutting_down;
3024 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08003025 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003026
3027 /* Now unmount the /data partition. */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07003028 if (wait_and_unmount(DATA_MNT_POINT, false)) {
JP Abgrall502dc742013-11-01 13:06:20 -07003029 if (allow_reboot) {
3030 goto error_shutting_down;
3031 } else {
3032 goto error_unencrypted;
3033 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003034 }
3035
3036 /* Do extra work for a better UX when doing the long inplace encryption */
3037 if (how == CRYPTO_ENABLE_INPLACE) {
3038 /* Now that /data is unmounted, we need to mount a tmpfs
3039 * /data, set a property saying we're doing inplace encryption,
3040 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003041 */
Ken Sumralle5032c42012-04-01 23:58:44 -07003042 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003043 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003044 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003045 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08003046 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003047
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003048 /* restart the framework. */
3049 /* Create necessary paths on /data */
3050 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003051 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003052 }
3053
Ken Sumrall92736ef2012-10-17 20:57:14 -07003054 /* Ugh, shutting down the framework is not synchronous, so until it
3055 * can be fixed, this horrible hack will wait a moment for it all to
3056 * shut down before proceeding. Without it, some devices cannot
3057 * restart the graphics services.
3058 */
3059 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003060 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003061
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003062 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003063 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence87999172014-02-20 12:21:31 -08003064 if (previously_encrypted_upto == 0) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07003065 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
3066 goto error_shutting_down;
3067 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003068
Paul Lawrence87999172014-02-20 12:21:31 -08003069 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
3070 crypt_ftr.fs_size = nr_sec
3071 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
3072 } else {
3073 crypt_ftr.fs_size = nr_sec;
3074 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07003075 /* At this point, we are in an inconsistent state. Until we successfully
3076 complete encryption, a reboot will leave us broken. So mark the
3077 encryption failed in case that happens.
3078 On successfully completing encryption, remove this flag */
3079 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence87999172014-02-20 12:21:31 -08003080 crypt_ftr.crypt_type = crypt_type;
Ajay Dudani87701e22014-09-17 21:02:52 -07003081#ifndef CONFIG_HW_DISK_ENCRYPTION
3082 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
3083#else
3084 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-xts", MAX_CRYPTO_TYPE_NAME_LEN);
3085
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08003086 rc = clear_hw_device_encryption_key();
Ajay Dudani87701e22014-09-17 21:02:52 -07003087 if (!rc) {
3088 SLOGE("Error clearing device encryption hardware key. rc = %d", rc);
3089 }
3090
3091 rc = set_hw_device_encryption_key(passwd,
3092 (char*) crypt_ftr.crypto_type_name);
3093 if (!rc) {
3094 SLOGE("Error initializing device encryption hardware key. rc = %d", rc);
3095 goto error_shutting_down;
3096 }
3097#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003098
Paul Lawrence87999172014-02-20 12:21:31 -08003099 /* Make an encrypted master key */
3100 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
3101 SLOGE("Cannot create encrypted master key\n");
3102 goto error_shutting_down;
3103 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003104
Paul Lawrence87999172014-02-20 12:21:31 -08003105 /* Write the key to the end of the partition */
3106 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003107
Paul Lawrence87999172014-02-20 12:21:31 -08003108 /* If any persistent data has been remembered, save it.
3109 * If none, create a valid empty table and save that.
3110 */
3111 if (!persist_data) {
3112 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
3113 if (pdata) {
3114 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
3115 persist_data = pdata;
3116 }
3117 }
3118 if (persist_data) {
3119 save_persistent_data();
3120 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003121 }
3122
Ajay Dudani87701e22014-09-17 21:02:52 -07003123 if (how == CRYPTO_ENABLE_INPLACE) {
3124 /* startup service classes main and late_start */
3125 property_set("vold.decrypt", "trigger_restart_min_framework");
3126 SLOGD("Just triggered restart_min_framework\n");
3127
3128 /* OK, the framework is restarted and will soon be showing a
3129 * progress bar. Time to setup an encrypted mapping, and
3130 * either write a new filesystem, or encrypt in place updating
3131 * the progress bar as we work.
3132 */
3133 }
3134
Paul Lawrenced0c7b172014-08-08 14:28:10 -07003135 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07003136 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
3137 "userdata");
3138
Paul Lawrence87999172014-02-20 12:21:31 -08003139 /* If we are continuing, check checksums match */
3140 rc = 0;
3141 if (previously_encrypted_upto) {
3142 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
3143 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07003144
Paul Lawrence87999172014-02-20 12:21:31 -08003145 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
3146 sizeof(hash_first_block)) != 0) {
3147 SLOGE("Checksums do not match - trigger wipe");
3148 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003149 }
3150 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003151
Paul Lawrence87999172014-02-20 12:21:31 -08003152 if (!rc) {
3153 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
3154 crypto_blkdev, real_blkdev,
3155 previously_encrypted_upto);
3156 }
3157
3158 /* Calculate checksum if we are not finished */
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003159 if (!rc && how == CRYPTO_ENABLE_INPLACE
3160 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003161 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
3162 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07003163 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08003164 SLOGE("Error calculating checksum for continuing encryption");
3165 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003166 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003167 }
3168
3169 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003170 delete_crypto_blk_dev("userdata");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003171
3172 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003173
3174 if (! rc) {
3175 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003176 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08003177
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003178 if (how == CRYPTO_ENABLE_INPLACE
3179 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003180 SLOGD("Encrypted up to sector %lld - will continue after reboot",
3181 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07003182 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08003183 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07003184
Paul Lawrence6bfed202014-07-28 12:47:22 -07003185 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08003186
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003187 if (how == CRYPTO_ENABLE_WIPE
3188 || crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003189 char value[PROPERTY_VALUE_MAX];
3190 property_get("ro.crypto.state", value, "");
3191 if (!strcmp(value, "")) {
3192 /* default encryption - continue first boot sequence */
3193 property_set("ro.crypto.state", "encrypted");
3194 release_wake_lock(lockid);
3195 cryptfs_check_passwd(DEFAULT_PASSWORD);
3196 cryptfs_restart_internal(1);
3197 return 0;
3198 } else {
3199 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08003200 cryptfs_reboot(reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003201 }
Paul Lawrence87999172014-02-20 12:21:31 -08003202 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003203 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Paul Lawrence87999172014-02-20 12:21:31 -08003204 cryptfs_reboot(shutdown);
3205 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003206 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003207 char value[PROPERTY_VALUE_MAX];
3208
Ken Sumrall319369a2012-06-27 16:30:18 -07003209 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003210 if (!strcmp(value, "1")) {
3211 /* wipe data if encryption failed */
3212 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
3213 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07003214 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003215 if (fd >= 0) {
Jeff Sharkeydd1a8042014-09-24 11:46:51 -07003216 write(fd, "--wipe_data\n", strlen("--wipe_data\n") + 1);
3217 write(fd, "--reason=cryptfs_enable_internal\n", strlen("--reason=cryptfs_enable_internal\n") + 1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003218 close(fd);
3219 } else {
3220 SLOGE("could not open /cache/recovery/command\n");
3221 }
Paul Lawrence87999172014-02-20 12:21:31 -08003222 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003223 } else {
3224 /* set property to trigger dialog */
3225 property_set("vold.encrypt_progress", "error_partially_encrypted");
3226 release_wake_lock(lockid);
3227 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003228 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003229 }
3230
Ken Sumrall3ed82362011-01-28 23:31:16 -08003231 /* hrm, the encrypt step claims success, but the reboot failed.
3232 * This should not happen.
3233 * Set the property and return. Hope the framework can deal with it.
3234 */
3235 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003236 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003237 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08003238
3239error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07003240 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003241 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003242 if (lockid[0]) {
3243 release_wake_lock(lockid);
3244 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003245 return -1;
3246
3247error_shutting_down:
3248 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3249 * but the framework is stopped and not restarted to show the error, so it's up to
3250 * vold to restart the system.
3251 */
3252 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08003253 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003254
3255 /* shouldn't get here */
3256 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003257 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003258 if (lockid[0]) {
3259 release_wake_lock(lockid);
3260 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003261 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003262}
3263
Paul Lawrence45f10532014-04-04 18:11:56 +00003264int cryptfs_enable(char *howarg, int type, char *passwd, int allow_reboot)
Paul Lawrence13486032014-02-03 13:28:11 -08003265{
Paul Lawrencefc615042014-10-04 15:32:29 -07003266 char* adjusted_passwd = adjust_passwd(passwd);
3267 if (adjusted_passwd) {
3268 passwd = adjusted_passwd;
3269 }
3270
3271 int rc = cryptfs_enable_internal(howarg, type, passwd, allow_reboot);
3272
3273 free(adjusted_passwd);
3274 return rc;
Paul Lawrence13486032014-02-03 13:28:11 -08003275}
3276
3277int cryptfs_enable_default(char *howarg, int allow_reboot)
3278{
3279 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
3280 DEFAULT_PASSWORD, allow_reboot);
3281}
3282
Paul Lawrence6a69cfc2015-01-21 09:58:26 -08003283static int device_is_force_encrypted() {
3284 int ret = -1;
3285 char value[PROP_VALUE_MAX];
3286 ret = __system_property_get("ro.vold.forceencryption", value);
3287 if (ret < 0)
3288 return 0;
3289 return strcmp(value, "1") ? 0 : 1;
3290}
3291
3292int cryptfs_maybe_enable_default_crypto()
3293{
3294 // Enable default crypt if /forceencrypt or /encryptable and
3295 // ro.vold.forceencrypt=1, else mount data and continue unencrypted
3296 struct fstab_rec *fstab_rec = 0;
3297 fstab_rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
3298 if (!fstab_rec) {
3299 SLOGE("Error getting fstab record");
3300 return -1;
3301 }
3302
3303 // See if we should encrypt?
3304 if ( !fs_mgr_is_encryptable(fstab_rec)
3305 || (!fs_mgr_is_force_encrypted(fstab_rec)
3306 && !device_is_force_encrypted())) {
3307 int rc = 0;
3308
3309 rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT, fstab_rec->blk_device, 0);
3310 property_set("vold.decrypt", "trigger_load_persist_props");
3311
3312 /* Create necessary paths on /data */
3313 if (prep_data_fs()) {
3314 return -1;
3315 }
3316
3317 property_set("ro.crypto.state", "unencrypted");
3318 property_set("vold.decrypt", "trigger_restart_framework");
3319 SLOGD("Unencrypted - restart_framework\n");
3320 return rc;
3321 }
3322
3323 return cryptfs_enable_default("inplace", 0);
3324}
3325
Paul Lawrence13486032014-02-03 13:28:11 -08003326int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003327{
3328 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003329
3330 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003331 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003332 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003333 return -1;
3334 }
3335
Paul Lawrencef4faa572014-01-29 13:31:03 -08003336 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3337 SLOGE("Invalid crypt_type %d", crypt_type);
3338 return -1;
3339 }
3340
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003341 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003342 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003343 SLOGE("Error getting crypt footer and key");
3344 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003345 }
3346
Paul Lawrencef4faa572014-01-29 13:31:03 -08003347 crypt_ftr.crypt_type = crypt_type;
3348
Paul Lawrencefc615042014-10-04 15:32:29 -07003349 char* adjusted_passwd = adjust_passwd(newpw);
3350 if (adjusted_passwd) {
3351 newpw = adjusted_passwd;
3352 }
3353
Paul Lawrencef4faa572014-01-29 13:31:03 -08003354 encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
3355 : newpw,
3356 crypt_ftr.salt,
3357 saved_master_key,
3358 crypt_ftr.master_key,
3359 &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003360
Jason parks70a4b3f2011-01-28 10:10:47 -06003361 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003362 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003363
Paul Lawrencefc615042014-10-04 15:32:29 -07003364 free(adjusted_passwd);
Ajay Dudani87701e22014-09-17 21:02:52 -07003365
3366#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08003367 if (!strcmp((char *)crypt_ftr.crypto_type_name, "aes-xts")) {
3368 if (crypt_type == CRYPT_TYPE_DEFAULT) {
3369 int rc = update_hw_device_encryption_key(DEFAULT_PASSWORD, (char*) crypt_ftr.crypto_type_name);
3370 SLOGD("Update hardware encryption key to default for crypt_type: %d. rc = %d", crypt_type, rc);
3371 if (!rc)
3372 return -1;
3373 } else {
3374 int rc = update_hw_device_encryption_key(newpw, (char*) crypt_ftr.crypto_type_name);
3375 SLOGD("Update hardware encryption key for crypt_type: %d. rc = %d", crypt_type, rc);
3376 if (!rc)
3377 return -1;
3378 }
Ajay Dudani87701e22014-09-17 21:02:52 -07003379 }
3380#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003381 return 0;
3382}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003383
Rubin Xu85c01f92014-10-13 12:49:54 +01003384static unsigned int persist_get_max_entries(int encrypted) {
3385 struct crypt_mnt_ftr crypt_ftr;
3386 unsigned int dsize;
3387 unsigned int max_persistent_entries;
3388
3389 /* If encrypted, use the values from the crypt_ftr, otherwise
3390 * use the values for the current spec.
3391 */
3392 if (encrypted) {
3393 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3394 return -1;
3395 }
3396 dsize = crypt_ftr.persist_data_size;
3397 } else {
3398 dsize = CRYPT_PERSIST_DATA_SIZE;
3399 }
3400
3401 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3402 sizeof(struct crypt_persist_entry);
3403
3404 return max_persistent_entries;
3405}
3406
3407static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003408{
3409 unsigned int i;
3410
3411 if (persist_data == NULL) {
3412 return -1;
3413 }
3414 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3415 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3416 /* We found it! */
3417 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3418 return 0;
3419 }
3420 }
3421
3422 return -1;
3423}
3424
Rubin Xu85c01f92014-10-13 12:49:54 +01003425static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003426{
3427 unsigned int i;
3428 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003429 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003430
3431 if (persist_data == NULL) {
3432 return -1;
3433 }
3434
Rubin Xu85c01f92014-10-13 12:49:54 +01003435 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003436
3437 num = persist_data->persist_valid_entries;
3438
3439 for (i = 0; i < num; i++) {
3440 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3441 /* We found an existing entry, update it! */
3442 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3443 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3444 return 0;
3445 }
3446 }
3447
3448 /* We didn't find it, add it to the end, if there is room */
3449 if (persist_data->persist_valid_entries < max_persistent_entries) {
3450 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3451 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3452 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3453 persist_data->persist_valid_entries++;
3454 return 0;
3455 }
3456
3457 return -1;
3458}
3459
Rubin Xu85c01f92014-10-13 12:49:54 +01003460/**
3461 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3462 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3463 */
3464static int match_multi_entry(const char *key, const char *field, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003465 unsigned int field_len;
3466 unsigned int key_index;
3467 field_len = strlen(field);
3468
3469 if (index == 0) {
3470 // The first key in a multi-entry field is just the filedname itself.
3471 if (!strcmp(key, field)) {
3472 return 1;
3473 }
3474 }
3475 // Match key against "%s_%d" % (field, index)
3476 if (strlen(key) < field_len + 1 + 1) {
3477 // Need at least a '_' and a digit.
3478 return 0;
3479 }
3480 if (strncmp(key, field, field_len)) {
3481 // If the key does not begin with field, it's not a match.
3482 return 0;
3483 }
3484 if (1 != sscanf(&key[field_len],"_%d", &key_index)) {
3485 return 0;
3486 }
3487 return key_index >= index;
3488}
3489
3490/*
3491 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3492 * remaining entries starting from index will be deleted.
3493 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3494 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3495 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3496 *
3497 */
3498static int persist_del_keys(const char *fieldname, unsigned index)
3499{
3500 unsigned int i;
3501 unsigned int j;
3502 unsigned int num;
3503
3504 if (persist_data == NULL) {
3505 return PERSIST_DEL_KEY_ERROR_OTHER;
3506 }
3507
3508 num = persist_data->persist_valid_entries;
3509
3510 j = 0; // points to the end of non-deleted entries.
3511 // Filter out to-be-deleted entries in place.
3512 for (i = 0; i < num; i++) {
3513 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3514 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3515 j++;
3516 }
3517 }
3518
3519 if (j < num) {
3520 persist_data->persist_valid_entries = j;
3521 // Zeroise the remaining entries
3522 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3523 return PERSIST_DEL_KEY_OK;
3524 } else {
3525 // Did not find an entry matching the given fieldname
3526 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3527 }
3528}
3529
3530static int persist_count_keys(const char *fieldname)
3531{
3532 unsigned int i;
3533 unsigned int count;
3534
3535 if (persist_data == NULL) {
3536 return -1;
3537 }
3538
3539 count = 0;
3540 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3541 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3542 count++;
3543 }
3544 }
3545
3546 return count;
3547}
3548
Ken Sumrall160b4d62013-04-22 12:15:39 -07003549/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003550int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003551{
3552 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003553 /* CRYPTO_GETFIELD_OK is success,
3554 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3555 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3556 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003557 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003558 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3559 int i;
3560 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003561
3562 if (persist_data == NULL) {
3563 load_persistent_data();
3564 if (persist_data == NULL) {
3565 SLOGE("Getfield error, cannot load persistent data");
3566 goto out;
3567 }
3568 }
3569
Rubin Xu85c01f92014-10-13 12:49:54 +01003570 // Read value from persistent entries. If the original value is split into multiple entries,
3571 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003572 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003573 // We found it, copy it to the caller's buffer and keep going until all entries are read.
3574 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
3575 // value too small
3576 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3577 goto out;
3578 }
3579 rc = CRYPTO_GETFIELD_OK;
3580
3581 for (i = 1; /* break explicitly */; i++) {
3582 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
3583 (int) sizeof(temp_field)) {
3584 // If the fieldname is very long, we stop as soon as it begins to overflow the
3585 // maximum field length. At this point we have in fact fully read out the original
3586 // value because cryptfs_setfield would not allow fields with longer names to be
3587 // written in the first place.
3588 break;
3589 }
3590 if (!persist_get_key(temp_field, temp_value)) {
3591 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3592 // value too small.
3593 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3594 goto out;
3595 }
3596 } else {
3597 // Exhaust all entries.
3598 break;
3599 }
3600 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003601 } else {
3602 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003603 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003604 }
3605
3606out:
3607 return rc;
3608}
3609
3610/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003611int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003612{
Ken Sumrall160b4d62013-04-22 12:15:39 -07003613 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003614 /* 0 is success, negative values are error */
3615 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003616 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003617 unsigned int field_id;
3618 char temp_field[PROPERTY_KEY_MAX];
3619 unsigned int num_entries;
3620 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003621
3622 if (persist_data == NULL) {
3623 load_persistent_data();
3624 if (persist_data == NULL) {
3625 SLOGE("Setfield error, cannot load persistent data");
3626 goto out;
3627 }
3628 }
3629
3630 property_get("ro.crypto.state", encrypted_state, "");
3631 if (!strcmp(encrypted_state, "encrypted") ) {
3632 encrypted = 1;
3633 }
3634
Rubin Xu85c01f92014-10-13 12:49:54 +01003635 // Compute the number of entries required to store value, each entry can store up to
3636 // (PROPERTY_VALUE_MAX - 1) chars
3637 if (strlen(value) == 0) {
3638 // Empty value also needs one entry to store.
3639 num_entries = 1;
3640 } else {
3641 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3642 }
3643
3644 max_keylen = strlen(fieldname);
3645 if (num_entries > 1) {
3646 // Need an extra "_%d" suffix.
3647 max_keylen += 1 + log10(num_entries);
3648 }
3649 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3650 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003651 goto out;
3652 }
3653
Rubin Xu85c01f92014-10-13 12:49:54 +01003654 // Make sure we have enough space to write the new value
3655 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3656 persist_get_max_entries(encrypted)) {
3657 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3658 goto out;
3659 }
3660
3661 // Now that we know persist_data has enough space for value, let's delete the old field first
3662 // to make up space.
3663 persist_del_keys(fieldname, 0);
3664
3665 if (persist_set_key(fieldname, value, encrypted)) {
3666 // fail to set key, should not happen as we have already checked the available space
3667 SLOGE("persist_set_key() error during setfield()");
3668 goto out;
3669 }
3670
3671 for (field_id = 1; field_id < num_entries; field_id++) {
3672 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
3673
3674 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3675 // fail to set key, should not happen as we have already checked the available space.
3676 SLOGE("persist_set_key() error during setfield()");
3677 goto out;
3678 }
3679 }
3680
Ken Sumrall160b4d62013-04-22 12:15:39 -07003681 /* If we are running encrypted, save the persistent data now */
3682 if (encrypted) {
3683 if (save_persistent_data()) {
3684 SLOGE("Setfield error, cannot save persistent data");
3685 goto out;
3686 }
3687 }
3688
Rubin Xu85c01f92014-10-13 12:49:54 +01003689 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003690
3691out:
3692 return rc;
3693}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003694
3695/* Checks userdata. Attempt to mount the volume if default-
3696 * encrypted.
3697 * On success trigger next init phase and return 0.
3698 * Currently do not handle failure - see TODO below.
3699 */
3700int cryptfs_mount_default_encrypted(void)
3701{
3702 char decrypt_state[PROPERTY_VALUE_MAX];
3703 property_get("vold.decrypt", decrypt_state, "0");
3704 if (!strcmp(decrypt_state, "0")) {
3705 SLOGE("Not encrypted - should not call here");
3706 } else {
3707 int crypt_type = cryptfs_get_password_type();
3708 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3709 SLOGE("Bad crypt type - error");
3710 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3711 SLOGD("Password is not default - "
3712 "starting min framework to prompt");
3713 property_set("vold.decrypt", "trigger_restart_min_framework");
3714 return 0;
3715 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3716 SLOGD("Password is default - restarting filesystem");
3717 cryptfs_restart_internal(0);
3718 return 0;
3719 } else {
3720 SLOGE("Encrypted, default crypt type but can't decrypt");
3721 }
3722 }
3723
Paul Lawrence6bfed202014-07-28 12:47:22 -07003724 /** Corrupt. Allow us to boot into framework, which will detect bad
3725 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003726 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003727 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003728 return 0;
3729}
3730
3731/* Returns type of the password, default, pattern, pin or password.
3732 */
3733int cryptfs_get_password_type(void)
3734{
3735 struct crypt_mnt_ftr crypt_ftr;
3736
3737 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3738 SLOGE("Error getting crypt footer and key\n");
3739 return -1;
3740 }
3741
Paul Lawrence6bfed202014-07-28 12:47:22 -07003742 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3743 return -1;
3744 }
3745
Paul Lawrencef4faa572014-01-29 13:31:03 -08003746 return crypt_ftr.crypt_type;
3747}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003748
Paul Lawrence399317e2014-03-10 13:20:50 -07003749char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003750{
Paul Lawrence399317e2014-03-10 13:20:50 -07003751 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003752 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003753 if (now.tv_sec < password_expiry_time) {
3754 return password;
3755 } else {
3756 cryptfs_clear_password();
3757 return 0;
3758 }
3759}
3760
3761void cryptfs_clear_password()
3762{
3763 if (password) {
3764 size_t len = strlen(password);
3765 memset(password, 0, len);
3766 free(password);
3767 password = 0;
3768 password_expiry_time = 0;
3769 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003770}