blob: f6dad2dd9ddf53f8aec518357fe2b717ac987d3a [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
23#include <sys/types.h>
Ken Sumralle550f782013-08-20 13:48:23 -070024#include <sys/wait.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080025#include <sys/stat.h>
Paul Lawrencef4faa572014-01-29 13:31:03 -080026#include <ctype.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080027#include <fcntl.h>
Elliott Hughes73737162014-06-25 17:27:42 -070028#include <inttypes.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080029#include <unistd.h>
30#include <stdio.h>
31#include <sys/ioctl.h>
32#include <linux/dm-ioctl.h>
33#include <libgen.h>
34#include <stdlib.h>
35#include <sys/param.h>
36#include <string.h>
37#include <sys/mount.h>
38#include <openssl/evp.h>
39#include <errno.h>
Ken Sumrall3ed82362011-01-28 23:31:16 -080040#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070041#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070042#include <fs_mgr.h>
Paul Lawrence9c58a872014-09-30 09:12:51 -070043#include <time.h>
Rubin Xu85c01f92014-10-13 12:49:54 +010044#include <math.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080045#include "cryptfs.h"
46#define LOG_TAG "Cryptfs"
47#include "cutils/log.h"
48#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070049#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080050#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070051#include <logwrap/logwrap.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070052#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070053#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070054#include "crypto_scrypt.h"
Paul Lawrenceae59fe62014-01-21 08:23:27 -080055#include "ext4_utils.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000056#include "f2fs_sparseblock.h"
Paul Lawrence87999172014-02-20 12:21:31 -080057#include "CheckBattery.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080058#include "Process.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080059
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070060#include <hardware/keymaster.h>
61
Mark Salyzyn3e971272014-01-21 13:27:04 -080062#define UNUSED __attribute__((unused))
63
Mark Salyzyn5eecc442014-02-12 14:16:14 -080064#define UNUSED __attribute__((unused))
65
Dinesh K Gargf58801b2014-01-13 14:16:47 -080066#ifdef CONFIG_HW_DISK_ENCRYPTION
67#include "cryptfs_hw.h"
68#endif
69
Ken Sumrall8f869aa2010-12-03 03:47:09 -080070#define DM_CRYPT_BUF_SIZE 4096
71
Jason parks70a4b3f2011-01-28 10:10:47 -060072#define HASH_COUNT 2000
73#define KEY_LEN_BYTES 16
74#define IV_LEN_BYTES 16
75
Ken Sumrall29d8da82011-05-18 17:20:07 -070076#define KEY_IN_FOOTER "footer"
77
Paul Lawrencef4faa572014-01-29 13:31:03 -080078// "default_password" encoded into hex (d=0x64 etc)
79#define DEFAULT_PASSWORD "64656661756c745f70617373776f7264"
80
Ken Sumrall29d8da82011-05-18 17:20:07 -070081#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070082#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070083
Ken Sumralle919efe2012-09-29 17:07:41 -070084#define TABLE_LOAD_RETRIES 10
85
Shawn Willden47ba10d2014-09-03 17:07:06 -060086#define RSA_KEY_SIZE 2048
87#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
88#define RSA_EXPONENT 0x10001
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070089
Paul Lawrence8e3f4512014-09-08 10:11:17 -070090#define RETRY_MOUNT_ATTEMPTS 10
91#define RETRY_MOUNT_DELAY_SECONDS 1
92
Ken Sumrall8f869aa2010-12-03 03:47:09 -080093char *me = "cryptfs";
94
Jason parks70a4b3f2011-01-28 10:10:47 -060095static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070096static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060097static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -070098static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -080099
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700100static int keymaster_init(keymaster_device_t **keymaster_dev)
101{
102 int rc;
103
104 const hw_module_t* mod;
105 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
106 if (rc) {
107 ALOGE("could not find any keystore module");
108 goto out;
109 }
110
111 rc = keymaster_open(mod, keymaster_dev);
112 if (rc) {
113 ALOGE("could not open keymaster device in %s (%s)",
114 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
115 goto out;
116 }
117
118 return 0;
119
120out:
121 *keymaster_dev = NULL;
122 return rc;
123}
124
125/* Should we use keymaster? */
126static int keymaster_check_compatibility()
127{
128 keymaster_device_t *keymaster_dev = 0;
129 int rc = 0;
130
131 if (keymaster_init(&keymaster_dev)) {
132 SLOGE("Failed to init keymaster");
133 rc = -1;
134 goto out;
135 }
136
Paul Lawrence8c008392014-05-06 14:02:48 -0700137 SLOGI("keymaster version is %d", keymaster_dev->common.module->module_api_version);
138
139 if (keymaster_dev->common.module->module_api_version
140 < KEYMASTER_MODULE_API_VERSION_0_3) {
141 rc = 0;
142 goto out;
143 }
144
Shawn Willden7c49ab02014-10-30 08:12:32 -0600145 if (!(keymaster_dev->flags & KEYMASTER_SOFTWARE_ONLY) &&
146 (keymaster_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE)) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700147 rc = 1;
148 }
149
150out:
151 keymaster_close(keymaster_dev);
152 return rc;
153}
154
155/* Create a new keymaster key and store it in this footer */
156static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
157{
158 uint8_t* key = 0;
159 keymaster_device_t *keymaster_dev = 0;
160
161 if (keymaster_init(&keymaster_dev)) {
162 SLOGE("Failed to init keymaster");
163 return -1;
164 }
165
166 int rc = 0;
167
168 keymaster_rsa_keygen_params_t params;
169 memset(&params, '\0', sizeof(params));
Shawn Willden47ba10d2014-09-03 17:07:06 -0600170 params.public_exponent = RSA_EXPONENT;
171 params.modulus_size = RSA_KEY_SIZE;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700172
173 size_t key_size;
174 if (keymaster_dev->generate_keypair(keymaster_dev, TYPE_RSA, &params,
175 &key, &key_size)) {
176 SLOGE("Failed to generate keypair");
177 rc = -1;
178 goto out;
179 }
180
181 if (key_size > KEYMASTER_BLOB_SIZE) {
182 SLOGE("Keymaster key too large for crypto footer");
183 rc = -1;
184 goto out;
185 }
186
187 memcpy(ftr->keymaster_blob, key, key_size);
188 ftr->keymaster_blob_size = key_size;
189
190out:
191 keymaster_close(keymaster_dev);
192 free(key);
193 return rc;
194}
195
Shawn Willdene17a9c42014-09-08 13:04:08 -0600196/* This signs the given object using the keymaster key. */
197static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600198 const unsigned char *object,
199 const size_t object_size,
200 unsigned char **signature,
201 size_t *signature_size)
202{
203 int rc = 0;
204 keymaster_device_t *keymaster_dev = 0;
205 if (keymaster_init(&keymaster_dev)) {
206 SLOGE("Failed to init keymaster");
207 return -1;
208 }
209
210 /* We currently set the digest type to DIGEST_NONE because it's the
211 * only supported value for keymaster. A similar issue exists with
212 * PADDING_NONE. Long term both of these should likely change.
213 */
214 keymaster_rsa_sign_params_t params;
215 params.digest_type = DIGEST_NONE;
216 params.padding_type = PADDING_NONE;
217
218 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600219 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600220 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600221
Shawn Willdene17a9c42014-09-08 13:04:08 -0600222 // To sign a message with RSA, the message must satisfy two
223 // constraints:
224 //
225 // 1. The message, when interpreted as a big-endian numeric value, must
226 // be strictly less than the public modulus of the RSA key. Note
227 // that because the most significant bit of the public modulus is
228 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
229 // key), an n-bit message with most significant bit 0 always
230 // satisfies this requirement.
231 //
232 // 2. The message must have the same length in bits as the public
233 // modulus of the RSA key. This requirement isn't mathematically
234 // necessary, but is necessary to ensure consistency in
235 // implementations.
236 switch (ftr->kdf_type) {
237 case KDF_SCRYPT_KEYMASTER_UNPADDED:
238 // This is broken: It produces a message which is shorter than
239 // the public modulus, failing criterion 2.
240 memcpy(to_sign, object, object_size);
241 to_sign_size = object_size;
242 SLOGI("Signing unpadded object");
243 break;
244 case KDF_SCRYPT_KEYMASTER_BADLY_PADDED:
245 // This is broken: Since the value of object is uniformly
246 // distributed, it produces a message that is larger than the
247 // public modulus with probability 0.25.
248 memcpy(to_sign, object, min(RSA_KEY_SIZE_BYTES, object_size));
249 SLOGI("Signing end-padded object");
250 break;
251 case KDF_SCRYPT_KEYMASTER:
252 // This ensures the most significant byte of the signed message
253 // is zero. We could have zero-padded to the left instead, but
254 // this approach is slightly more robust against changes in
255 // object size. However, it's still broken (but not unusably
256 // so) because we really should be using a proper RSA padding
257 // function, such as OAEP.
258 //
259 // TODO(paullawrence): When keymaster 0.4 is available, change
260 // this to use the padding options it provides.
261 memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
262 SLOGI("Signing safely-padded object");
263 break;
264 default:
265 SLOGE("Unknown KDF type %d", ftr->kdf_type);
266 return -1;
267 }
268
Shawn Willden47ba10d2014-09-03 17:07:06 -0600269 rc = keymaster_dev->sign_data(keymaster_dev,
270 &params,
271 ftr->keymaster_blob,
272 ftr->keymaster_blob_size,
273 to_sign,
Shawn Willdene17a9c42014-09-08 13:04:08 -0600274 to_sign_size,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600275 signature,
276 signature_size);
277
278 keymaster_close(keymaster_dev);
279 return rc;
280}
281
Paul Lawrence399317e2014-03-10 13:20:50 -0700282/* Store password when userdata is successfully decrypted and mounted.
283 * Cleared by cryptfs_clear_password
284 *
285 * To avoid a double prompt at boot, we need to store the CryptKeeper
286 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
287 * Since the entire framework is torn down and rebuilt after encryption,
288 * we have to use a daemon or similar to store the password. Since vold
289 * is secured against IPC except from system processes, it seems a reasonable
290 * place to store this.
291 *
292 * password should be cleared once it has been used.
293 *
294 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800295 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700296static char* password = 0;
297static int password_expiry_time = 0;
298static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800299
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800300extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800301
Paul Lawrence87999172014-02-20 12:21:31 -0800302enum RebootType {reboot, recovery, shutdown};
303static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700304{
Paul Lawrence87999172014-02-20 12:21:31 -0800305 switch(rt) {
306 case reboot:
307 property_set(ANDROID_RB_PROPERTY, "reboot");
308 break;
309
310 case recovery:
311 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
312 break;
313
314 case shutdown:
315 property_set(ANDROID_RB_PROPERTY, "shutdown");
316 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700317 }
Paul Lawrence87999172014-02-20 12:21:31 -0800318
Ken Sumralladfba362013-06-04 16:37:52 -0700319 sleep(20);
320
321 /* Shouldn't get here, reboot should happen before sleep times out */
322 return;
323}
324
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800325static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
326{
327 memset(io, 0, dataSize);
328 io->data_size = dataSize;
329 io->data_start = sizeof(struct dm_ioctl);
330 io->version[0] = 4;
331 io->version[1] = 0;
332 io->version[2] = 0;
333 io->flags = flags;
334 if (name) {
335 strncpy(io->name, name, sizeof(io->name));
336 }
337}
338
Kenny Rootc4c70f12013-06-14 12:11:38 -0700339/**
340 * Gets the default device scrypt parameters for key derivation time tuning.
341 * The parameters should lead to about one second derivation time for the
342 * given device.
343 */
344static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
345 const int default_params[] = SCRYPT_DEFAULTS;
346 int params[] = SCRYPT_DEFAULTS;
347 char paramstr[PROPERTY_VALUE_MAX];
348 char *token;
349 char *saveptr;
350 int i;
351
352 property_get(SCRYPT_PROP, paramstr, "");
353 if (paramstr[0] != '\0') {
354 /*
355 * The token we're looking for should be three integers separated by
356 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
357 */
Kenny Root2947e342013-08-14 15:54:49 -0700358 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
359 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700360 i++, token = strtok_r(NULL, ":", &saveptr)) {
361 char *endptr;
362 params[i] = strtol(token, &endptr, 10);
363
364 /*
365 * Check that there was a valid number and it's 8-bit. If not,
366 * break out and the end check will take the default values.
367 */
368 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
369 break;
370 }
371 }
372
373 /*
374 * If there were not enough tokens or a token was malformed (not an
375 * integer), it will end up here and the default parameters can be
376 * taken.
377 */
378 if ((i != 3) || (token != NULL)) {
379 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
380 memcpy(params, default_params, sizeof(params));
381 }
382 }
383
384 ftr->N_factor = params[0];
385 ftr->r_factor = params[1];
386 ftr->p_factor = params[2];
387}
388
Ken Sumrall3ed82362011-01-28 23:31:16 -0800389static unsigned int get_fs_size(char *dev)
390{
391 int fd, block_size;
392 struct ext4_super_block sb;
393 off64_t len;
394
395 if ((fd = open(dev, O_RDONLY)) < 0) {
396 SLOGE("Cannot open device to get filesystem size ");
397 return 0;
398 }
399
400 if (lseek64(fd, 1024, SEEK_SET) < 0) {
401 SLOGE("Cannot seek to superblock");
402 return 0;
403 }
404
405 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
406 SLOGE("Cannot read superblock");
407 return 0;
408 }
409
410 close(fd);
411
Daniel Rosenberge82df162014-08-15 22:19:23 +0000412 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
413 SLOGE("Not a valid ext4 superblock");
414 return 0;
415 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800416 block_size = 1024 << sb.s_log_block_size;
417 /* compute length in bytes */
418 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
419
420 /* return length in sectors */
421 return (unsigned int) (len / 512);
422}
423
Ken Sumrall160b4d62013-04-22 12:15:39 -0700424static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
425{
426 static int cached_data = 0;
427 static off64_t cached_off = 0;
428 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
429 int fd;
430 char key_loc[PROPERTY_VALUE_MAX];
431 char real_blkdev[PROPERTY_VALUE_MAX];
432 unsigned int nr_sec;
433 int rc = -1;
434
435 if (!cached_data) {
436 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
437
438 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
439 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
440 SLOGE("Cannot open real block device %s\n", real_blkdev);
441 return -1;
442 }
443
444 if ((nr_sec = get_blkdev_size(fd))) {
445 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
446 * encryption info footer and key, and plenty of bytes to spare for future
447 * growth.
448 */
449 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
450 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
451 cached_data = 1;
452 } else {
453 SLOGE("Cannot get size of block device %s\n", real_blkdev);
454 }
455 close(fd);
456 } else {
457 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
458 cached_off = 0;
459 cached_data = 1;
460 }
461 }
462
463 if (cached_data) {
464 if (metadata_fname) {
465 *metadata_fname = cached_metadata_fname;
466 }
467 if (off) {
468 *off = cached_off;
469 }
470 rc = 0;
471 }
472
473 return rc;
474}
475
Ken Sumralle8744072011-01-18 22:01:55 -0800476/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800477 * update the failed mount count but not change the key.
478 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700479static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800480{
481 int fd;
482 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700483 /* starting_off is set to the SEEK_SET offset
484 * where the crypto structure starts
485 */
486 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800487 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700488 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700489 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800490
Ken Sumrall160b4d62013-04-22 12:15:39 -0700491 if (get_crypt_ftr_info(&fname, &starting_off)) {
492 SLOGE("Unable to get crypt_ftr_info\n");
493 return -1;
494 }
495 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700496 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700497 return -1;
498 }
Ken Sumralle550f782013-08-20 13:48:23 -0700499 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
500 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700501 return -1;
502 }
503
504 /* Seek to the start of the crypt footer */
505 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
506 SLOGE("Cannot seek to real block device footer\n");
507 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800508 }
509
510 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
511 SLOGE("Cannot write real block device footer\n");
512 goto errout;
513 }
514
Ken Sumrall3be890f2011-09-14 16:53:46 -0700515 fstat(fd, &statbuf);
516 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700517 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700518 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800519 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800520 goto errout;
521 }
522 }
523
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800524 /* Success! */
525 rc = 0;
526
527errout:
528 close(fd);
529 return rc;
530
531}
532
Ken Sumrall160b4d62013-04-22 12:15:39 -0700533static inline int unix_read(int fd, void* buff, int len)
534{
535 return TEMP_FAILURE_RETRY(read(fd, buff, len));
536}
537
538static inline int unix_write(int fd, const void* buff, int len)
539{
540 return TEMP_FAILURE_RETRY(write(fd, buff, len));
541}
542
543static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
544{
545 memset(pdata, 0, len);
546 pdata->persist_magic = PERSIST_DATA_MAGIC;
547 pdata->persist_valid_entries = 0;
548}
549
550/* A routine to update the passed in crypt_ftr to the lastest version.
551 * fd is open read/write on the device that holds the crypto footer and persistent
552 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
553 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
554 */
555static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
556{
Kenny Root7434b312013-06-14 11:29:53 -0700557 int orig_major = crypt_ftr->major_version;
558 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700559
Kenny Root7434b312013-06-14 11:29:53 -0700560 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
561 struct crypt_persist_data *pdata;
562 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700563
Kenny Rootc4c70f12013-06-14 12:11:38 -0700564 SLOGW("upgrading crypto footer to 1.1");
565
Kenny Root7434b312013-06-14 11:29:53 -0700566 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
567 if (pdata == NULL) {
568 SLOGE("Cannot allocate persisent data\n");
569 return;
570 }
571 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
572
573 /* Need to initialize the persistent data area */
574 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
575 SLOGE("Cannot seek to persisent data offset\n");
576 return;
577 }
578 /* Write all zeros to the first copy, making it invalid */
579 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
580
581 /* Write a valid but empty structure to the second copy */
582 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
583 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
584
585 /* Update the footer */
586 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
587 crypt_ftr->persist_data_offset[0] = pdata_offset;
588 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
589 crypt_ftr->minor_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700590 }
591
Paul Lawrencef4faa572014-01-29 13:31:03 -0800592 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700593 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800594 /* But keep the old kdf_type.
595 * It will get updated later to KDF_SCRYPT after the password has been verified.
596 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700597 crypt_ftr->kdf_type = KDF_PBKDF2;
598 get_device_scrypt_params(crypt_ftr);
599 crypt_ftr->minor_version = 2;
600 }
601
Paul Lawrencef4faa572014-01-29 13:31:03 -0800602 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
603 SLOGW("upgrading crypto footer to 1.3");
604 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
605 crypt_ftr->minor_version = 3;
Lalit Kansaraed9f3d82014-12-31 10:52:21 +0530606 /* Here if we get CRYPT_DATA_CORRUPT flag set (i.e. 0x8) then it means
607 * CRYPT_FDE_COMPLETED flag was set in actual for crypto footer version 1.2.
608 * Now while upgrading footer to 1.3, we need to reset CRYPT_DATA_CORRUPT flag
609 * and set CRYPT_FDE_COMPLETED flag back.
610 */
611 if (crypt_ftr->flags & CRYPT_DATA_CORRUPT) {
612 crypt_ftr->flags &= ~CRYPT_DATA_CORRUPT;
613 crypt_ftr->flags |= CRYPT_FDE_COMPLETED;
614 }
615 /* Here if we get CRYPT_INCONSISTENT_STATE flag set (i.e. 0x4) then it means
616 * CRYPT_PFE_ACTIVATED flag was set in actual for crypto footer version 1.2.
617 * Now while upgrading footer to 1.3, we need to reset CRYPT_INCONSISTENT_STATE
618 * flag and set CRYPT_PFE_ACTIVATED flag back.
619 */
620 if (crypt_ftr->flags & CRYPT_INCONSISTENT_STATE) {
621 crypt_ftr->flags &= ~CRYPT_INCONSISTENT_STATE;
622 crypt_ftr->flags |= CRYPT_PFE_ACTIVATED;
623 }
Paul Lawrencef4faa572014-01-29 13:31:03 -0800624 }
625
Kenny Root7434b312013-06-14 11:29:53 -0700626 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
627 if (lseek64(fd, offset, SEEK_SET) == -1) {
628 SLOGE("Cannot seek to crypt footer\n");
629 return;
630 }
631 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700632 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700633}
634
635
636static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800637{
638 int fd;
639 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700640 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800641 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700642 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700643 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800644
Ken Sumrall160b4d62013-04-22 12:15:39 -0700645 if (get_crypt_ftr_info(&fname, &starting_off)) {
646 SLOGE("Unable to get crypt_ftr_info\n");
647 return -1;
648 }
649 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700650 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700651 return -1;
652 }
653 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700654 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700655 return -1;
656 }
657
658 /* Make sure it's 16 Kbytes in length */
659 fstat(fd, &statbuf);
660 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
661 SLOGE("footer file %s is not the expected size!\n", fname);
662 goto errout;
663 }
664
665 /* Seek to the start of the crypt footer */
666 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
667 SLOGE("Cannot seek to real block device footer\n");
668 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800669 }
670
671 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
672 SLOGE("Cannot read real block device footer\n");
673 goto errout;
674 }
675
676 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700677 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800678 goto errout;
679 }
680
Kenny Rootc96a5f82013-06-14 12:08:28 -0700681 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
682 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
683 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800684 goto errout;
685 }
686
Kenny Rootc96a5f82013-06-14 12:08:28 -0700687 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
688 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
689 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800690 }
691
Ken Sumrall160b4d62013-04-22 12:15:39 -0700692 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
693 * copy on disk before returning.
694 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700695 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700696 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800697 }
698
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800699 /* Success! */
700 rc = 0;
701
702errout:
703 close(fd);
704 return rc;
705}
706
Ken Sumrall160b4d62013-04-22 12:15:39 -0700707static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
708{
709 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
710 crypt_ftr->persist_data_offset[1]) {
711 SLOGE("Crypt_ftr persist data regions overlap");
712 return -1;
713 }
714
715 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
716 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
717 return -1;
718 }
719
720 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
721 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
722 CRYPT_FOOTER_OFFSET) {
723 SLOGE("Persistent data extends past crypto footer");
724 return -1;
725 }
726
727 return 0;
728}
729
730static int load_persistent_data(void)
731{
732 struct crypt_mnt_ftr crypt_ftr;
733 struct crypt_persist_data *pdata = NULL;
734 char encrypted_state[PROPERTY_VALUE_MAX];
735 char *fname;
736 int found = 0;
737 int fd;
738 int ret;
739 int i;
740
741 if (persist_data) {
742 /* Nothing to do, we've already loaded or initialized it */
743 return 0;
744 }
745
746
747 /* If not encrypted, just allocate an empty table and initialize it */
748 property_get("ro.crypto.state", encrypted_state, "");
749 if (strcmp(encrypted_state, "encrypted") ) {
750 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
751 if (pdata) {
752 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
753 persist_data = pdata;
754 return 0;
755 }
756 return -1;
757 }
758
759 if(get_crypt_ftr_and_key(&crypt_ftr)) {
760 return -1;
761 }
762
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700763 if ((crypt_ftr.major_version < 1)
764 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700765 SLOGE("Crypt_ftr version doesn't support persistent data");
766 return -1;
767 }
768
769 if (get_crypt_ftr_info(&fname, NULL)) {
770 return -1;
771 }
772
773 ret = validate_persistent_data_storage(&crypt_ftr);
774 if (ret) {
775 return -1;
776 }
777
778 fd = open(fname, O_RDONLY);
779 if (fd < 0) {
780 SLOGE("Cannot open %s metadata file", fname);
781 return -1;
782 }
783
784 if (persist_data == NULL) {
785 pdata = malloc(crypt_ftr.persist_data_size);
786 if (pdata == NULL) {
787 SLOGE("Cannot allocate memory for persistent data");
788 goto err;
789 }
790 }
791
792 for (i = 0; i < 2; i++) {
793 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
794 SLOGE("Cannot seek to read persistent data on %s", fname);
795 goto err2;
796 }
797 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
798 SLOGE("Error reading persistent data on iteration %d", i);
799 goto err2;
800 }
801 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
802 found = 1;
803 break;
804 }
805 }
806
807 if (!found) {
808 SLOGI("Could not find valid persistent data, creating");
809 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
810 }
811
812 /* Success */
813 persist_data = pdata;
814 close(fd);
815 return 0;
816
817err2:
818 free(pdata);
819
820err:
821 close(fd);
822 return -1;
823}
824
825static int save_persistent_data(void)
826{
827 struct crypt_mnt_ftr crypt_ftr;
828 struct crypt_persist_data *pdata;
829 char *fname;
830 off64_t write_offset;
831 off64_t erase_offset;
832 int found = 0;
833 int fd;
834 int ret;
835
836 if (persist_data == NULL) {
837 SLOGE("No persistent data to save");
838 return -1;
839 }
840
841 if(get_crypt_ftr_and_key(&crypt_ftr)) {
842 return -1;
843 }
844
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700845 if ((crypt_ftr.major_version < 1)
846 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700847 SLOGE("Crypt_ftr version doesn't support persistent data");
848 return -1;
849 }
850
851 ret = validate_persistent_data_storage(&crypt_ftr);
852 if (ret) {
853 return -1;
854 }
855
856 if (get_crypt_ftr_info(&fname, NULL)) {
857 return -1;
858 }
859
860 fd = open(fname, O_RDWR);
861 if (fd < 0) {
862 SLOGE("Cannot open %s metadata file", fname);
863 return -1;
864 }
865
866 pdata = malloc(crypt_ftr.persist_data_size);
867 if (pdata == NULL) {
868 SLOGE("Cannot allocate persistant data");
869 goto err;
870 }
871
872 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
873 SLOGE("Cannot seek to read persistent data on %s", fname);
874 goto err2;
875 }
876
877 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
878 SLOGE("Error reading persistent data before save");
879 goto err2;
880 }
881
882 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
883 /* The first copy is the curent valid copy, so write to
884 * the second copy and erase this one */
885 write_offset = crypt_ftr.persist_data_offset[1];
886 erase_offset = crypt_ftr.persist_data_offset[0];
887 } else {
888 /* The second copy must be the valid copy, so write to
889 * the first copy, and erase the second */
890 write_offset = crypt_ftr.persist_data_offset[0];
891 erase_offset = crypt_ftr.persist_data_offset[1];
892 }
893
894 /* Write the new copy first, if successful, then erase the old copy */
895 if (lseek(fd, write_offset, SEEK_SET) < 0) {
896 SLOGE("Cannot seek to write persistent data");
897 goto err2;
898 }
899 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
900 (int) crypt_ftr.persist_data_size) {
901 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
902 SLOGE("Cannot seek to erase previous persistent data");
903 goto err2;
904 }
905 fsync(fd);
906 memset(pdata, 0, crypt_ftr.persist_data_size);
907 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
908 (int) crypt_ftr.persist_data_size) {
909 SLOGE("Cannot write to erase previous persistent data");
910 goto err2;
911 }
912 fsync(fd);
913 } else {
914 SLOGE("Cannot write to save persistent data");
915 goto err2;
916 }
917
918 /* Success */
919 free(pdata);
920 close(fd);
921 return 0;
922
923err2:
924 free(pdata);
925err:
926 close(fd);
927 return -1;
928}
929
Paul Lawrencef4faa572014-01-29 13:31:03 -0800930static int hexdigit (char c)
931{
932 if (c >= '0' && c <= '9') return c - '0';
933 c = tolower(c);
934 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
935 return -1;
936}
937
938static unsigned char* convert_hex_ascii_to_key(const char* master_key_ascii,
939 unsigned int* out_keysize)
940{
941 unsigned int i;
942 *out_keysize = 0;
943
944 size_t size = strlen (master_key_ascii);
945 if (size % 2) {
946 SLOGE("Trying to convert ascii string of odd length");
947 return NULL;
948 }
949
950 unsigned char* master_key = (unsigned char*) malloc(size / 2);
951 if (master_key == 0) {
952 SLOGE("Cannot allocate");
953 return NULL;
954 }
955
956 for (i = 0; i < size; i += 2) {
957 int high_nibble = hexdigit (master_key_ascii[i]);
958 int low_nibble = hexdigit (master_key_ascii[i + 1]);
959
960 if(high_nibble < 0 || low_nibble < 0) {
961 SLOGE("Invalid hex string");
962 free (master_key);
963 return NULL;
964 }
965
966 master_key[*out_keysize] = high_nibble * 16 + low_nibble;
967 (*out_keysize)++;
968 }
969
970 return master_key;
971}
972
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800973/* Convert a binary key of specified length into an ascii hex string equivalent,
974 * without the leading 0x and with null termination
975 */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800976static void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800977 char *master_key_ascii)
978{
979 unsigned int i, a;
980 unsigned char nibble;
981
982 for (i=0, a=0; i<keysize; i++, a+=2) {
983 /* For each byte, write out two ascii hex digits */
984 nibble = (master_key[i] >> 4) & 0xf;
985 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
986
987 nibble = master_key[i] & 0xf;
988 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
989 }
990
991 /* Add the null termination */
992 master_key_ascii[a] = '\0';
993
994}
995
Ken Sumralldb5e0262013-02-05 17:39:48 -0800996static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
997 char *real_blk_name, const char *name, int fd,
998 char *extra_params)
999{
1000 char buffer[DM_CRYPT_BUF_SIZE];
1001 struct dm_ioctl *io;
1002 struct dm_target_spec *tgt;
1003 char *crypt_params;
1004 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
1005 int i;
1006
1007 io = (struct dm_ioctl *) buffer;
1008
1009 /* Load the mapping table for this device */
1010 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
1011
1012 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1013 io->target_count = 1;
1014 tgt->status = 0;
1015 tgt->sector_start = 0;
1016 tgt->length = crypt_ftr->fs_size;
Dinesh K Gargf58801b2014-01-13 14:16:47 -08001017#ifdef CONFIG_HW_DISK_ENCRYPTION
1018 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name))
1019 strlcpy(tgt->target_type, "req-crypt",DM_MAX_TYPE_NAME);
1020 else
1021 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1022#else
Ken Sumralldb5e0262013-02-05 17:39:48 -08001023 strcpy(tgt->target_type, "crypt");
Dinesh K Gargf58801b2014-01-13 14:16:47 -08001024#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001025
1026 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
Dinesh K Gargdb2b1ed2014-10-08 16:20:03 -07001027#ifdef CONFIG_HW_DISK_ENCRYPTION
1028 if (is_ice_enabled())
1029 convert_key_to_hex_ascii(master_key, sizeof(int), master_key_ascii);
1030 else
1031 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1032#else
Ken Sumralldb5e0262013-02-05 17:39:48 -08001033 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
Dinesh K Gargdb2b1ed2014-10-08 16:20:03 -07001034#endif
1035 sprintf(crypt_params, "%s %s 0 %s 0 %s 0", crypt_ftr->crypto_type_name,
Ken Sumralldb5e0262013-02-05 17:39:48 -08001036 master_key_ascii, real_blk_name, extra_params);
Divya Sharma6a6d5cc2014-09-18 16:14:46 +03001037
1038 SLOGI("%s: target_type = %s\n", __func__, tgt->target_type);
Divya Sharmae248fd82014-10-07 16:38:57 +03001039 SLOGI("%s: real_blk_name = %s, extra_params = %s\n", __func__, real_blk_name, extra_params);
Divya Sharma6a6d5cc2014-09-18 16:14:46 +03001040
Ken Sumralldb5e0262013-02-05 17:39:48 -08001041 crypt_params += strlen(crypt_params) + 1;
1042 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1043 tgt->next = crypt_params - buffer;
1044
1045 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1046 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
1047 break;
1048 }
1049 usleep(500000);
1050 }
1051
1052 if (i == TABLE_LOAD_RETRIES) {
1053 /* We failed to load the table, return an error */
1054 return -1;
1055 } else {
1056 return i + 1;
1057 }
1058}
1059
1060
1061static int get_dm_crypt_version(int fd, const char *name, int *version)
1062{
1063 char buffer[DM_CRYPT_BUF_SIZE];
1064 struct dm_ioctl *io;
1065 struct dm_target_versions *v;
1066 int i;
1067
1068 io = (struct dm_ioctl *) buffer;
1069
1070 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1071
1072 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1073 return -1;
1074 }
1075
1076 /* Iterate over the returned versions, looking for name of "crypt".
1077 * When found, get and return the version.
1078 */
1079 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1080 while (v->next) {
Dinesh K Gargf58801b2014-01-13 14:16:47 -08001081#ifdef CONFIG_HW_DISK_ENCRYPTION
1082 if(!strcmp(v->name, "crypt") || !strcmp(v->name, "req-crypt")) {
1083#else
Ken Sumralldb5e0262013-02-05 17:39:48 -08001084 if (! strcmp(v->name, "crypt")) {
Dinesh K Gargf58801b2014-01-13 14:16:47 -08001085#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001086 /* We found the crypt driver, return the version, and get out */
1087 version[0] = v->version[0];
1088 version[1] = v->version[1];
1089 version[2] = v->version[2];
1090 return 0;
1091 }
1092 v = (struct dm_target_versions *)(((char *)v) + v->next);
1093 }
1094
1095 return -1;
1096}
1097
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001098static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -07001099 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001100{
1101 char buffer[DM_CRYPT_BUF_SIZE];
1102 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
1103 char *crypt_params;
1104 struct dm_ioctl *io;
1105 struct dm_target_spec *tgt;
1106 unsigned int minor;
Dinesh K Gargf58801b2014-01-13 14:16:47 -08001107 int fd=0;
Ken Sumralle919efe2012-09-29 17:07:41 -07001108 int i;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001109 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001110 int version[3];
1111 char *extra_params;
1112 int load_count;
Dinesh K Gargf58801b2014-01-13 14:16:47 -08001113#ifdef CONFIG_HW_DISK_ENCRYPTION
1114 char encrypted_state[PROPERTY_VALUE_MAX] = {0};
1115 char progress[PROPERTY_VALUE_MAX] = {0};
1116#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001117
1118 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1119 SLOGE("Cannot open device-mapper\n");
1120 goto errout;
1121 }
1122
1123 io = (struct dm_ioctl *) buffer;
1124
1125 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1126 if (ioctl(fd, DM_DEV_CREATE, io)) {
1127 SLOGE("Cannot create dm-crypt device\n");
1128 goto errout;
1129 }
1130
1131 /* Get the device status, in particular, the name of it's device file */
1132 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1133 if (ioctl(fd, DM_DEV_STATUS, io)) {
1134 SLOGE("Cannot retrieve dm-crypt device status\n");
1135 goto errout;
1136 }
1137 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1138 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1139
Dinesh K Gargf58801b2014-01-13 14:16:47 -08001140#ifdef CONFIG_HW_DISK_ENCRYPTION
1141 /* Set fde_enabled if either FDE completed or in-progress */
1142 property_get("ro.crypto.state", encrypted_state, ""); /* FDE completed */
1143 property_get("vold.encrypt_progress", progress, ""); /* FDE in progress */
Dinesh K Gargdb2b1ed2014-10-08 16:20:03 -07001144 if (!strcmp(encrypted_state, "encrypted") || strcmp(progress, "")) {
1145 if (is_ice_enabled())
1146 extra_params = "fde_enabled ice";
1147 else
Dinesh K Gargf58801b2014-01-13 14:16:47 -08001148 extra_params = "fde_enabled";
Dinesh K Gargdb2b1ed2014-10-08 16:20:03 -07001149 }
Dinesh K Gargf58801b2014-01-13 14:16:47 -08001150 else
1151 extra_params = "fde_disabled";
1152#else
Ken Sumralldb5e0262013-02-05 17:39:48 -08001153 extra_params = "";
1154 if (! get_dm_crypt_version(fd, name, version)) {
1155 /* Support for allow_discards was added in version 1.11.0 */
1156 if ((version[0] >= 2) ||
1157 ((version[0] == 1) && (version[1] >= 11))) {
1158 extra_params = "1 allow_discards";
1159 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1160 }
Ken Sumralle919efe2012-09-29 17:07:41 -07001161 }
Dinesh K Gargf58801b2014-01-13 14:16:47 -08001162#endif
Ken Sumralle919efe2012-09-29 17:07:41 -07001163
Ken Sumralldb5e0262013-02-05 17:39:48 -08001164 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1165 fd, extra_params);
1166 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001167 SLOGE("Cannot load dm-crypt mapping table.\n");
1168 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001169 } else if (load_count > 1) {
1170 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001171 }
1172
1173 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -08001174 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001175
1176 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1177 SLOGE("Cannot resume the dm-crypt device\n");
1178 goto errout;
1179 }
1180
1181 /* We made it here with no errors. Woot! */
1182 retval = 0;
1183
1184errout:
1185 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1186
1187 return retval;
1188}
1189
Ken Sumrall29d8da82011-05-18 17:20:07 -07001190static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001191{
1192 int fd;
1193 char buffer[DM_CRYPT_BUF_SIZE];
1194 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001195 int retval = -1;
1196
1197 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1198 SLOGE("Cannot open device-mapper\n");
1199 goto errout;
1200 }
1201
1202 io = (struct dm_ioctl *) buffer;
1203
1204 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1205 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1206 SLOGE("Cannot remove dm-crypt device\n");
1207 goto errout;
1208 }
1209
1210 /* We made it here with no errors. Woot! */
1211 retval = 0;
1212
1213errout:
1214 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1215
1216 return retval;
1217
1218}
1219
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001220static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001221 unsigned char *ikey, void *params UNUSED)
1222{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001223 SLOGI("Using pbkdf2 for cryptfs KDF");
1224
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001225 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001226 unsigned int keysize;
1227 char* master_key = (char*)convert_hex_ascii_to_key(passwd, &keysize);
1228 if (!master_key) return -1;
1229 PKCS5_PBKDF2_HMAC_SHA1(master_key, keysize, salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001230 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001231
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001232 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001233 free (master_key);
1234 return 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001235}
1236
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001237static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001238 unsigned char *ikey, void *params)
1239{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001240 SLOGI("Using scrypt for cryptfs KDF");
1241
Kenny Rootc4c70f12013-06-14 12:11:38 -07001242 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1243
1244 int N = 1 << ftr->N_factor;
1245 int r = 1 << ftr->r_factor;
1246 int p = 1 << ftr->p_factor;
1247
1248 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001249 unsigned int keysize;
1250 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &keysize);
1251 if (!master_key) return -1;
1252 crypto_scrypt(master_key, keysize, salt, SALT_LEN, N, r, p, ikey,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001253 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001254
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001255 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001256 free (master_key);
1257 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001258}
1259
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001260static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1261 unsigned char *ikey, void *params)
1262{
1263 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1264
1265 int rc;
1266 unsigned int key_size;
1267 size_t signature_size;
1268 unsigned char* signature;
1269 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1270
1271 int N = 1 << ftr->N_factor;
1272 int r = 1 << ftr->r_factor;
1273 int p = 1 << ftr->p_factor;
1274
1275 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &key_size);
1276 if (!master_key) {
1277 SLOGE("Failed to convert passwd from hex");
1278 return -1;
1279 }
1280
1281 rc = crypto_scrypt(master_key, key_size, salt, SALT_LEN,
1282 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1283 memset(master_key, 0, key_size);
1284 free(master_key);
1285
1286 if (rc) {
1287 SLOGE("scrypt failed");
1288 return -1;
1289 }
1290
Shawn Willdene17a9c42014-09-08 13:04:08 -06001291 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1292 &signature, &signature_size)) {
1293 SLOGE("Signing failed");
1294 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001295 }
1296
1297 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1298 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1299 free(signature);
1300
1301 if (rc) {
1302 SLOGE("scrypt failed");
1303 return -1;
1304 }
1305
1306 return 0;
1307}
1308
1309static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1310 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001311 unsigned char *encrypted_master_key,
1312 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001313{
1314 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1315 EVP_CIPHER_CTX e_ctx;
1316 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001317 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001318
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001319 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001320 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001321
1322 switch (crypt_ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001323 case KDF_SCRYPT_KEYMASTER_UNPADDED:
1324 case KDF_SCRYPT_KEYMASTER_BADLY_PADDED:
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001325 case KDF_SCRYPT_KEYMASTER:
1326 if (keymaster_create_key(crypt_ftr)) {
1327 SLOGE("keymaster_create_key failed");
1328 return -1;
1329 }
1330
1331 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1332 SLOGE("scrypt failed");
1333 return -1;
1334 }
1335 break;
1336
1337 case KDF_SCRYPT:
1338 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1339 SLOGE("scrypt failed");
1340 return -1;
1341 }
1342 break;
1343
1344 default:
1345 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001346 return -1;
1347 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001348
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001349 /* Initialize the decryption engine */
1350 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1351 SLOGE("EVP_EncryptInit failed\n");
1352 return -1;
1353 }
1354 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001355
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001356 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001357 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
1358 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001359 SLOGE("EVP_EncryptUpdate failed\n");
1360 return -1;
1361 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001362 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001363 SLOGE("EVP_EncryptFinal failed\n");
1364 return -1;
1365 }
1366
1367 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1368 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1369 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001370 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001371
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001372 /* Store the scrypt of the intermediate key, so we can validate if it's a
1373 password error or mount error when things go wrong.
1374 Note there's no need to check for errors, since if this is incorrect, we
1375 simply won't wipe userdata, which is the correct default behavior
1376 */
1377 int N = 1 << crypt_ftr->N_factor;
1378 int r = 1 << crypt_ftr->r_factor;
1379 int p = 1 << crypt_ftr->p_factor;
1380
1381 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1382 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1383 crypt_ftr->scrypted_intermediate_key,
1384 sizeof(crypt_ftr->scrypted_intermediate_key));
1385
1386 if (rc) {
1387 SLOGE("encrypt_master_key: crypto_scrypt failed");
1388 }
1389
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001390 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001391}
1392
JP Abgrall7bdfa522013-11-15 13:42:56 -08001393static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001394 unsigned char *encrypted_master_key,
1395 unsigned char *decrypted_master_key,
1396 kdf_func kdf, void *kdf_params,
1397 unsigned char** intermediate_key,
1398 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001399{
1400 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 -08001401 EVP_CIPHER_CTX d_ctx;
1402 int decrypted_len, final_len;
1403
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001404 /* Turn the password into an intermediate key and IV that can decrypt the
1405 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001406 if (kdf(passwd, salt, ikey, kdf_params)) {
1407 SLOGE("kdf failed");
1408 return -1;
1409 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001410
1411 /* Initialize the decryption engine */
1412 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1413 return -1;
1414 }
1415 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1416 /* Decrypt the master key */
1417 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1418 encrypted_master_key, KEY_LEN_BYTES)) {
1419 return -1;
1420 }
1421 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1422 return -1;
1423 }
1424
1425 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1426 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001427 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001428
1429 /* Copy intermediate key if needed by params */
1430 if (intermediate_key && intermediate_key_size) {
1431 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1432 if (intermediate_key) {
1433 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1434 *intermediate_key_size = KEY_LEN_BYTES;
1435 }
1436 }
1437
1438 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001439}
1440
Kenny Rootc4c70f12013-06-14 12:11:38 -07001441static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001442{
Shawn Willdene17a9c42014-09-08 13:04:08 -06001443 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER_UNPADDED ||
1444 ftr->kdf_type == KDF_SCRYPT_KEYMASTER_BADLY_PADDED ||
1445 ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001446 *kdf = scrypt_keymaster;
1447 *kdf_params = ftr;
1448 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001449 *kdf = scrypt;
1450 *kdf_params = ftr;
1451 } else {
1452 *kdf = pbkdf2;
1453 *kdf_params = NULL;
1454 }
1455}
1456
JP Abgrall7bdfa522013-11-15 13:42:56 -08001457static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001458 struct crypt_mnt_ftr *crypt_ftr,
1459 unsigned char** intermediate_key,
1460 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001461{
1462 kdf_func kdf;
1463 void *kdf_params;
1464 int ret;
1465
1466 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001467 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1468 decrypted_master_key, kdf, kdf_params,
1469 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001470 if (ret != 0) {
1471 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001472 }
1473
1474 return ret;
1475}
1476
1477static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1478 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001479 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001480 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001481 EVP_CIPHER_CTX e_ctx;
1482 int encrypted_len, final_len;
1483
1484 /* Get some random bits for a key */
1485 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001486 read(fd, key_buf, sizeof(key_buf));
1487 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001488 close(fd);
1489
1490 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001491 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001492}
1493
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001494static int wait_and_unmount(char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001495{
Greg Hackmann955653e2014-09-24 14:55:20 -07001496 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001497#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001498
1499 /* Now umount the tmpfs filesystem */
1500 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001501 if (umount(mountpoint) == 0) {
1502 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001503 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001504
1505 if (errno == EINVAL) {
1506 /* EINVAL is returned if the directory is not a mountpoint,
1507 * i.e. there is no filesystem mounted there. So just get out.
1508 */
1509 break;
1510 }
1511
1512 err = errno;
1513
1514 /* If allowed, be increasingly aggressive before the last two retries */
1515 if (kill) {
1516 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1517 SLOGW("sending SIGHUP to processes with open files\n");
1518 vold_killProcessesWithOpenFiles(mountpoint, 1);
1519 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1520 SLOGW("sending SIGKILL to processes with open files\n");
1521 vold_killProcessesWithOpenFiles(mountpoint, 2);
1522 }
1523 }
1524
1525 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001526 }
1527
1528 if (i < WAIT_UNMOUNT_COUNT) {
1529 SLOGD("unmounting %s succeeded\n", mountpoint);
1530 rc = 0;
1531 } else {
jessica_yu3f14fe42014-09-22 15:57:40 +08001532 vold_killProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001533 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001534 rc = -1;
1535 }
1536
1537 return rc;
1538}
1539
Ken Sumrallc5872692013-05-14 15:26:31 -07001540#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001541static int prep_data_fs(void)
1542{
1543 int i;
1544
1545 /* Do the prep of the /data filesystem */
1546 property_set("vold.post_fs_data_done", "0");
1547 property_set("vold.decrypt", "trigger_post_fs_data");
1548 SLOGD("Just triggered post_fs_data\n");
1549
Ken Sumrallc5872692013-05-14 15:26:31 -07001550 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001551 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001552 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001553
1554 property_get("vold.post_fs_data_done", p, "0");
1555 if (*p == '1') {
1556 break;
1557 } else {
1558 usleep(250000);
1559 }
1560 }
1561 if (i == DATA_PREP_TIMEOUT) {
1562 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001563 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001564 return -1;
1565 } else {
1566 SLOGD("post_fs_data done\n");
1567 return 0;
1568 }
1569}
1570
Paul Lawrence74f29f12014-08-28 15:54:10 -07001571static void cryptfs_set_corrupt()
1572{
1573 // Mark the footer as bad
1574 struct crypt_mnt_ftr crypt_ftr;
1575 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1576 SLOGE("Failed to get crypto footer - panic");
1577 return;
1578 }
1579
1580 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1581 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1582 SLOGE("Failed to set crypto footer - panic");
1583 return;
1584 }
1585}
1586
1587static void cryptfs_trigger_restart_min_framework()
1588{
1589 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1590 SLOGE("Failed to mount tmpfs on data - panic");
1591 return;
1592 }
1593
1594 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1595 SLOGE("Failed to trigger post fs data - panic");
1596 return;
1597 }
1598
1599 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1600 SLOGE("Failed to trigger restart min framework - panic");
1601 return;
1602 }
1603}
1604
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001605/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001606static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001607{
1608 char fs_type[32];
1609 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001610 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001611 char fs_options[256];
1612 unsigned long mnt_flags;
1613 struct stat statbuf;
1614 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001615 static int restart_successful = 0;
1616
1617 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001618 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001619 SLOGE("Encrypted filesystem not validated, aborting");
1620 return -1;
1621 }
1622
1623 if (restart_successful) {
1624 SLOGE("System already restarted with encrypted disk, aborting");
1625 return -1;
1626 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001627
Paul Lawrencef4faa572014-01-29 13:31:03 -08001628 if (restart_main) {
1629 /* Here is where we shut down the framework. The init scripts
1630 * start all services in one of three classes: core, main or late_start.
1631 * On boot, we start core and main. Now, we stop main, but not core,
1632 * as core includes vold and a few other really important things that
1633 * we need to keep running. Once main has stopped, we should be able
1634 * to umount the tmpfs /data, then mount the encrypted /data.
1635 * We then restart the class main, and also the class late_start.
1636 * At the moment, I've only put a few things in late_start that I know
1637 * are not needed to bring up the framework, and that also cause problems
1638 * with unmounting the tmpfs /data, but I hope to add add more services
1639 * to the late_start class as we optimize this to decrease the delay
1640 * till the user is asked for the password to the filesystem.
1641 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001642
Paul Lawrencef4faa572014-01-29 13:31:03 -08001643 /* The init files are setup to stop the class main when vold.decrypt is
1644 * set to trigger_reset_main.
1645 */
1646 property_set("vold.decrypt", "trigger_reset_main");
1647 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001648
Paul Lawrencef4faa572014-01-29 13:31:03 -08001649 /* Ugh, shutting down the framework is not synchronous, so until it
1650 * can be fixed, this horrible hack will wait a moment for it all to
1651 * shut down before proceeding. Without it, some devices cannot
1652 * restart the graphics services.
1653 */
1654 sleep(2);
1655 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001656
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001657 /* Now that the framework is shutdown, we should be able to umount()
1658 * the tmpfs filesystem, and mount the real one.
1659 */
1660
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001661 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1662 if (strlen(crypto_blkdev) == 0) {
1663 SLOGE("fs_crypto_blkdev not set\n");
1664 return -1;
1665 }
1666
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001667 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001668 /* If ro.crypto.readonly is set to 1, mount the decrypted
1669 * filesystem readonly. This is used when /data is mounted by
1670 * recovery mode.
1671 */
1672 char ro_prop[PROPERTY_VALUE_MAX];
1673 property_get("ro.crypto.readonly", ro_prop, "");
1674 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1675 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1676 rec->flags |= MS_RDONLY;
1677 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001678
Ken Sumralle5032c42012-04-01 23:58:44 -07001679 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001680 int retries = RETRY_MOUNT_ATTEMPTS;
1681 int mount_rc;
1682 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1683 crypto_blkdev, 0))
1684 != 0) {
1685 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1686 /* TODO: invoke something similar to
1687 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1688 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1689 SLOGI("Failed to mount %s because it is busy - waiting",
1690 crypto_blkdev);
1691 if (--retries) {
1692 sleep(RETRY_MOUNT_DELAY_SECONDS);
1693 } else {
1694 /* Let's hope that a reboot clears away whatever is keeping
1695 the mount busy */
1696 cryptfs_reboot(reboot);
1697 }
1698 } else {
1699 SLOGE("Failed to mount decrypted data");
1700 cryptfs_set_corrupt();
1701 cryptfs_trigger_restart_min_framework();
1702 SLOGI("Started framework to offer wipe");
1703 return -1;
1704 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001705 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001706
Ken Sumralle5032c42012-04-01 23:58:44 -07001707 property_set("vold.decrypt", "trigger_load_persist_props");
1708 /* Create necessary paths on /data */
1709 if (prep_data_fs()) {
1710 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001711 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001712
1713 /* startup service classes main and late_start */
1714 property_set("vold.decrypt", "trigger_restart_framework");
1715 SLOGD("Just triggered restart_framework\n");
1716
1717 /* Give it a few moments to get started */
1718 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001719 }
1720
Ken Sumrall0cc16632011-01-18 20:32:26 -08001721 if (rc == 0) {
1722 restart_successful = 1;
1723 }
1724
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001725 return rc;
1726}
1727
Paul Lawrencef4faa572014-01-29 13:31:03 -08001728int cryptfs_restart(void)
1729{
1730 /* Call internal implementation forcing a restart of main service group */
1731 return cryptfs_restart_internal(1);
1732}
1733
Mark Salyzyn3e971272014-01-21 13:27:04 -08001734static int do_crypto_complete(char *mount_point UNUSED)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001735{
1736 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001737 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001738 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001739
1740 property_get("ro.crypto.state", encrypted_state, "");
1741 if (strcmp(encrypted_state, "encrypted") ) {
1742 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001743 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001744 }
1745
Ken Sumrall160b4d62013-04-22 12:15:39 -07001746 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001747 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001748
Ken Sumralle1a45852011-12-14 21:24:27 -08001749 /*
1750 * Only report this error if key_loc is a file and it exists.
1751 * If the device was never encrypted, and /data is not mountable for
1752 * some reason, returning 1 should prevent the UI from presenting the
1753 * a "enter password" screen, or worse, a "press button to wipe the
1754 * device" screen.
1755 */
1756 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1757 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001758 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001759 } else {
1760 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001761 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001762 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001763 }
1764
Paul Lawrence74f29f12014-08-28 15:54:10 -07001765 // Test for possible error flags
1766 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1767 SLOGE("Encryption process is partway completed\n");
1768 return CRYPTO_COMPLETE_PARTIAL;
1769 }
1770
1771 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1772 SLOGE("Encryption process was interrupted but cannot continue\n");
1773 return CRYPTO_COMPLETE_INCONSISTENT;
1774 }
1775
1776 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1777 SLOGE("Encryption is successful but data is corrupt\n");
1778 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001779 }
1780
1781 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001782 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001783}
1784
Paul Lawrencef4faa572014-01-29 13:31:03 -08001785static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1786 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001787{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001788 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001789 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001790 char crypto_blkdev[MAXPATHLEN];
1791 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001792 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001793 unsigned int orig_failed_decrypt_count;
1794 int rc;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001795 kdf_func kdf;
1796 void *kdf_params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001797 int use_keymaster = 0;
1798 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001799 unsigned char* intermediate_key = 0;
1800 size_t intermediate_key_size = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001801
Paul Lawrencef4faa572014-01-29 13:31:03 -08001802 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1803 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001804
Paul Lawrencef4faa572014-01-29 13:31:03 -08001805 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001806 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1807 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001808 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001809 rc = -1;
1810 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001811 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001812 }
1813
Paul Lawrencef4faa572014-01-29 13:31:03 -08001814 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1815
Dinesh K Gargf58801b2014-01-13 14:16:47 -08001816#ifdef CONFIG_HW_DISK_ENCRYPTION
Dinesh K Gargdb2b1ed2014-10-08 16:20:03 -07001817 int key_index = 0;
1818 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1819 key_index = set_hw_device_encryption_key(passwd, (char*) crypt_ftr->crypto_type_name);
1820 if (key_index < 0) {
Dinesh K Gargd31a8092014-09-24 08:59:41 -07001821 rc = -1;
Dinesh K Gargdb2b1ed2014-10-08 16:20:03 -07001822 }
1823 else {
1824 if (is_ice_enabled()) {
1825 if (create_crypto_blk_dev(crypt_ftr, &key_index,
1826 real_blkdev, crypto_blkdev, label)) {
1827 SLOGE("Error creating decrypted block device\n");
1828 rc = -1;
1829 goto errout;
1830 }
1831 } else {
1832 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1833 real_blkdev, crypto_blkdev, label)) {
1834 SLOGE("Error creating decrypted block device\n");
1835 rc = -1;
1836 goto errout;
1837 }
1838 }
1839 }
1840 } else {
1841 /* in case HW FDE is delivered through OTA and device is already encrypted
1842 * using SW FDE, we should let user continue using SW FDE until userdata is
1843 * wiped.
1844 */
1845 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1846 real_blkdev, crypto_blkdev, label)) {
1847 SLOGE("Error creating decrypted block device\n");
1848 rc = -1;
1849 goto errout;
1850 }
1851 }
1852#else
Paul Lawrence74f29f12014-08-28 15:54:10 -07001853 // Create crypto block device - all (non fatal) code paths
1854 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001855 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1856 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001857 SLOGE("Error creating decrypted block device\n");
1858 rc = -1;
1859 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001860 }
Dinesh K Gargdb2b1ed2014-10-08 16:20:03 -07001861#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001862
Paul Lawrence74f29f12014-08-28 15:54:10 -07001863 /* Work out if the problem is the password or the data */
1864 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1865 scrypted_intermediate_key)];
1866 int N = 1 << crypt_ftr->N_factor;
1867 int r = 1 << crypt_ftr->r_factor;
1868 int p = 1 << crypt_ftr->p_factor;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001869
Paul Lawrence74f29f12014-08-28 15:54:10 -07001870 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1871 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1872 N, r, p, scrypted_intermediate_key,
1873 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001874
Paul Lawrence74f29f12014-08-28 15:54:10 -07001875 // Does the key match the crypto footer?
1876 if (rc == 0 && memcmp(scrypted_intermediate_key,
1877 crypt_ftr->scrypted_intermediate_key,
1878 sizeof(scrypted_intermediate_key)) == 0) {
1879 SLOGI("Password matches");
1880 rc = 0;
1881 } else {
1882 /* Try mounting the file system anyway, just in case the problem's with
1883 * the footer, not the key. */
1884 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1885 mkdir(tmp_mount_point, 0755);
1886 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1887 SLOGE("Error temp mounting decrypted block device\n");
1888 delete_crypto_blk_dev(label);
1889
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001890 rc = ++crypt_ftr->failed_decrypt_count;
1891 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001892 } else {
1893 /* Success! */
1894 SLOGI("Password did not match but decrypted drive mounted - continue");
1895 umount(tmp_mount_point);
1896 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001897 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001898 }
1899
1900 if (rc == 0) {
1901 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001902 if (orig_failed_decrypt_count != 0) {
1903 put_crypt_ftr_and_key(crypt_ftr);
1904 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001905
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001906 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001907 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001908 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001909
1910 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001911 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001912 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001913 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001914 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001915 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001916 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001917
Paul Lawrence74f29f12014-08-28 15:54:10 -07001918 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001919 use_keymaster = keymaster_check_compatibility();
1920 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001921 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001922 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1923 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1924 upgrade = 1;
1925 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001926 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001927 upgrade = 1;
1928 }
1929
1930 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001931 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1932 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001933 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001934 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001935 }
1936 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001937
1938 // Do not fail even if upgrade failed - machine is bootable
1939 // Note that if this code is ever hit, there is a *serious* problem
1940 // since KDFs should never fail. You *must* fix the kdf before
1941 // proceeding!
1942 if (rc) {
1943 SLOGW("Upgrade failed with error %d,"
1944 " but continuing with previous state",
1945 rc);
1946 rc = 0;
1947 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001948 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001949 }
1950
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001951 errout:
1952 if (intermediate_key) {
1953 memset(intermediate_key, 0, intermediate_key_size);
1954 free(intermediate_key);
1955 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001956 return rc;
1957}
1958
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001959/* Called by vold when it wants to undo the crypto mapping of a volume it
1960 * manages. This is usually in response to a factory reset, when we want
1961 * to undo the crypto mapping so the volume is formatted in the clear.
1962 */
1963int cryptfs_revert_volume(const char *label)
1964{
1965 return delete_crypto_blk_dev((char *)label);
1966}
1967
Ken Sumrall29d8da82011-05-18 17:20:07 -07001968/*
1969 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1970 * Setup a dm-crypt mapping, use the saved master key from
1971 * setting up the /data mapping, and return the new device path.
1972 */
1973int cryptfs_setup_volume(const char *label, int major, int minor,
1974 char *crypto_sys_path, unsigned int max_path,
1975 int *new_major, int *new_minor)
1976{
1977 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1978 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001979 struct stat statbuf;
1980 int nr_sec, fd;
1981
1982 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1983
Ken Sumrall160b4d62013-04-22 12:15:39 -07001984 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001985
1986 /* Update the fs_size field to be the size of the volume */
1987 fd = open(real_blkdev, O_RDONLY);
1988 nr_sec = get_blkdev_size(fd);
1989 close(fd);
1990 if (nr_sec == 0) {
1991 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1992 return -1;
1993 }
1994
1995 sd_crypt_ftr.fs_size = nr_sec;
1996 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1997 crypto_blkdev, label);
1998
JP Abgrall3334c6a2014-10-10 15:52:11 -07001999 if (stat(crypto_blkdev, &statbuf) < 0) {
2000 SLOGE("Error get stat for crypto_blkdev %s. err=%d(%s)\n",
2001 crypto_blkdev, errno, strerror(errno));
2002 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07002003 *new_major = MAJOR(statbuf.st_rdev);
2004 *new_minor = MINOR(statbuf.st_rdev);
2005
2006 /* Create path to sys entry for this block device */
2007 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
2008
2009 return 0;
2010}
2011
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002012int cryptfs_crypto_complete(void)
2013{
2014 return do_crypto_complete("/data");
2015}
2016
Paul Lawrencef4faa572014-01-29 13:31:03 -08002017int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
2018{
2019 char encrypted_state[PROPERTY_VALUE_MAX];
2020 property_get("ro.crypto.state", encrypted_state, "");
2021 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
2022 SLOGE("encrypted fs already validated or not running with encryption,"
2023 " aborting");
2024 return -1;
2025 }
2026
2027 if (get_crypt_ftr_and_key(crypt_ftr)) {
2028 SLOGE("Error getting crypt footer and key");
2029 return -1;
2030 }
2031
2032 return 0;
2033}
2034
Paul Lawrencefc615042014-10-04 15:32:29 -07002035/*
2036 * TODO - transition patterns to new format in calling code
2037 * and remove this vile hack, and the use of hex in
2038 * the password passing code.
2039 *
2040 * Patterns are passed in zero based (i.e. the top left dot
2041 * is represented by zero, the top middle one etc), but we want
2042 * to store them '1' based.
2043 * This is to allow us to migrate the calling code to use this
2044 * convention. It also solves a nasty problem whereby scrypt ignores
2045 * trailing zeros, so patterns ending at the top left could be
2046 * truncated, and similarly, you could add the top left to any
2047 * pattern and still match.
2048 * adjust_passwd is a hack function that returns the alternate representation
2049 * if the password appears to be a pattern (hex numbers all less than 09)
2050 * If it succeeds we need to try both, and in particular try the alternate
2051 * first. If the original matches, then we need to update the footer
2052 * with the alternate.
2053 * All code that accepts passwords must adjust them first. Since
2054 * cryptfs_check_passwd is always the first function called after a migration
2055 * (and indeed on any boot) we only need to do the double try in this
2056 * function.
2057 */
2058char* adjust_passwd(const char* passwd)
2059{
2060 size_t index, length;
2061
2062 if (!passwd) {
2063 return 0;
2064 }
2065
2066 // Check even length. Hex encoded passwords are always
2067 // an even length, since each character encodes to two characters.
2068 length = strlen(passwd);
2069 if (length % 2) {
2070 SLOGW("Password not correctly hex encoded.");
2071 return 0;
2072 }
2073
2074 // Check password is old-style pattern - a collection of hex
2075 // encoded bytes less than 9 (00 through 08)
2076 for (index = 0; index < length; index +=2) {
2077 if (passwd[index] != '0'
2078 || passwd[index + 1] < '0' || passwd[index + 1] > '8') {
2079 return 0;
2080 }
2081 }
2082
2083 // Allocate room for adjusted passwd and null terminate
2084 char* adjusted = malloc(length + 1);
2085 adjusted[length] = 0;
2086
2087 // Add 0x31 ('1') to each character
2088 for (index = 0; index < length; index += 2) {
2089 // output is 31 through 39 so set first byte to three, second to src + 1
2090 adjusted[index] = '3';
2091 adjusted[index + 1] = passwd[index + 1] + 1;
2092 }
2093
2094 return adjusted;
2095}
2096
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002097int cryptfs_check_passwd(char *passwd)
2098{
Paul Lawrencef4faa572014-01-29 13:31:03 -08002099 struct crypt_mnt_ftr crypt_ftr;
2100 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002101
Paul Lawrencef4faa572014-01-29 13:31:03 -08002102 rc = check_unmounted_and_get_ftr(&crypt_ftr);
2103 if (rc)
2104 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002105
Paul Lawrencefc615042014-10-04 15:32:29 -07002106 char* adjusted_passwd = adjust_passwd(passwd);
2107 if (adjusted_passwd) {
2108 int failed_decrypt_count = crypt_ftr.failed_decrypt_count;
2109 rc = test_mount_encrypted_fs(&crypt_ftr, adjusted_passwd,
2110 DATA_MNT_POINT, "userdata");
2111
2112 // Maybe the original one still works?
2113 if (rc) {
2114 // Don't double count this failure
2115 crypt_ftr.failed_decrypt_count = failed_decrypt_count;
2116 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
2117 DATA_MNT_POINT, "userdata");
2118 if (!rc) {
2119 // cryptfs_changepw also adjusts so pass original
2120 // Note that adjust_passwd only recognises patterns
2121 // so we can safely use CRYPT_TYPE_PATTERN
2122 SLOGI("Updating pattern to new format");
2123 cryptfs_changepw(CRYPT_TYPE_PATTERN, passwd);
2124 }
2125 }
2126 free(adjusted_passwd);
2127 } else {
2128 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
2129 DATA_MNT_POINT, "userdata");
2130 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002131
2132 if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002133 cryptfs_clear_password();
2134 password = strdup(passwd);
2135 struct timespec now;
2136 clock_gettime(CLOCK_BOOTTIME, &now);
2137 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002138 }
2139
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002140 return rc;
2141}
2142
Ken Sumrall3ad90722011-10-04 20:38:29 -07002143int cryptfs_verify_passwd(char *passwd)
2144{
2145 struct crypt_mnt_ftr crypt_ftr;
2146 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002147 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002148 char encrypted_state[PROPERTY_VALUE_MAX];
2149 int rc;
2150
2151 property_get("ro.crypto.state", encrypted_state, "");
2152 if (strcmp(encrypted_state, "encrypted") ) {
2153 SLOGE("device not encrypted, aborting");
2154 return -2;
2155 }
2156
2157 if (!master_key_saved) {
2158 SLOGE("encrypted fs not yet mounted, aborting");
2159 return -1;
2160 }
2161
2162 if (!saved_mount_point) {
2163 SLOGE("encrypted fs failed to save mount point, aborting");
2164 return -1;
2165 }
2166
Ken Sumrall160b4d62013-04-22 12:15:39 -07002167 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002168 SLOGE("Error getting crypt footer and key\n");
2169 return -1;
2170 }
2171
2172 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2173 /* If the device has no password, then just say the password is valid */
2174 rc = 0;
2175 } else {
Paul Lawrencefc615042014-10-04 15:32:29 -07002176 char* adjusted_passwd = adjust_passwd(passwd);
2177 if (adjusted_passwd) {
2178 passwd = adjusted_passwd;
2179 }
2180
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002181 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002182 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2183 /* They match, the password is correct */
2184 rc = 0;
2185 } else {
2186 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2187 sleep(1);
2188 rc = 1;
2189 }
Paul Lawrencefc615042014-10-04 15:32:29 -07002190
2191 free(adjusted_passwd);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002192 }
2193
2194 return rc;
2195}
2196
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002197/* Initialize a crypt_mnt_ftr structure. The keysize is
2198 * defaulted to 16 bytes, and the filesystem size to 0.
2199 * Presumably, at a minimum, the caller will update the
2200 * filesystem size and crypto_type_name after calling this function.
2201 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002202static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002203{
Ken Sumrall160b4d62013-04-22 12:15:39 -07002204 off64_t off;
2205
2206 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002207 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002208 ftr->major_version = CURRENT_MAJOR_VERSION;
2209 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002210 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06002211 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002212
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002213 switch (keymaster_check_compatibility()) {
2214 case 1:
2215 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2216 break;
2217
2218 case 0:
2219 ftr->kdf_type = KDF_SCRYPT;
2220 break;
2221
2222 default:
2223 SLOGE("keymaster_check_compatibility failed");
2224 return -1;
2225 }
2226
Kenny Rootc4c70f12013-06-14 12:11:38 -07002227 get_device_scrypt_params(ftr);
2228
Ken Sumrall160b4d62013-04-22 12:15:39 -07002229 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2230 if (get_crypt_ftr_info(NULL, &off) == 0) {
2231 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
2232 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
2233 ftr->persist_data_size;
2234 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002235
2236 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002237}
2238
Ken Sumrall29d8da82011-05-18 17:20:07 -07002239static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002240{
Ken Sumralle550f782013-08-20 13:48:23 -07002241 const char *args[10];
2242 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
2243 int num_args;
2244 int status;
2245 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002246 int rc = -1;
2247
Ken Sumrall29d8da82011-05-18 17:20:07 -07002248 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07002249 args[0] = "/system/bin/make_ext4fs";
2250 args[1] = "-a";
2251 args[2] = "/data";
2252 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07002253 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07002254 args[4] = size_str;
2255 args[5] = crypto_blkdev;
2256 num_args = 6;
2257 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
2258 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07002259 } else if (type == F2FS_FS) {
2260 args[0] = "/system/bin/mkfs.f2fs";
2261 args[1] = "-t";
2262 args[2] = "-d1";
2263 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07002264 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07002265 args[4] = size_str;
2266 num_args = 5;
2267 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
2268 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002269 } else {
2270 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
2271 return -1;
2272 }
2273
Ken Sumralle550f782013-08-20 13:48:23 -07002274 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
2275
2276 if (tmp != 0) {
2277 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002278 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07002279 if (WIFEXITED(status)) {
2280 if (WEXITSTATUS(status)) {
2281 SLOGE("Error creating filesystem on %s, exit status %d ",
2282 crypto_blkdev, WEXITSTATUS(status));
2283 } else {
2284 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
2285 rc = 0;
2286 }
2287 } else {
2288 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
2289 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002290 }
2291
2292 return rc;
2293}
2294
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002295#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08002296#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
2297#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002298
2299/* aligned 32K writes tends to make flash happy.
2300 * SD card association recommends it.
2301 */
Ajay Dudani87701e22014-09-17 21:02:52 -07002302#ifndef CONFIG_HW_DISK_ENCRYPTION
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002303#define BLOCKS_AT_A_TIME 8
Ajay Dudani87701e22014-09-17 21:02:52 -07002304#else
2305#define BLOCKS_AT_A_TIME 1024
2306#endif
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002307
David Ng5d636d42015-02-27 18:41:19 -08002308/* Number of blocks to write before an explicit flush
2309 to reduce disk buffer usage during inplace encryption
2310 */
2311#define BLOCKS_BEFORE_FLUSH 128
2312
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002313struct encryptGroupsData
2314{
2315 int realfd;
2316 int cryptofd;
2317 off64_t numblocks;
2318 off64_t one_pct, cur_pct, new_pct;
2319 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002320 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002321 char* real_blkdev, * crypto_blkdev;
2322 int count;
2323 off64_t offset;
2324 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08002325 off64_t last_written_sector;
2326 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002327 time_t time_started;
2328 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002329};
2330
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002331static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002332{
2333 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002334
2335 if (is_used) {
2336 data->used_blocks_already_done++;
2337 }
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002338 if (data->tot_used_blocks) {
2339 data->new_pct = data->used_blocks_already_done / data->one_pct;
2340 } else {
2341 data->new_pct = data->blocks_already_done / data->one_pct;
2342 }
2343
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002344 if (data->new_pct > data->cur_pct) {
2345 char buf[8];
2346 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07002347 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002348 property_set("vold.encrypt_progress", buf);
2349 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002350
2351 if (data->cur_pct >= 5) {
Paul Lawrence9c58a872014-09-30 09:12:51 -07002352 struct timespec time_now;
2353 if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
2354 SLOGW("Error getting time");
2355 } else {
2356 double elapsed_time = difftime(time_now.tv_sec, data->time_started);
2357 off64_t remaining_blocks = data->tot_used_blocks
2358 - data->used_blocks_already_done;
2359 int remaining_time = (int)(elapsed_time * remaining_blocks
2360 / data->used_blocks_already_done);
Paul Lawrence71577502014-08-13 14:55:55 -07002361
Paul Lawrence9c58a872014-09-30 09:12:51 -07002362 // Change time only if not yet set, lower, or a lot higher for
2363 // best user experience
2364 if (data->remaining_time == -1
2365 || remaining_time < data->remaining_time
2366 || remaining_time > data->remaining_time + 60) {
2367 char buf[8];
2368 snprintf(buf, sizeof(buf), "%d", remaining_time);
2369 property_set("vold.encrypt_time_remaining", buf);
2370 data->remaining_time = remaining_time;
2371 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002372 }
2373 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002374}
2375
Paul Lawrence3846be12014-09-22 11:33:54 -07002376static void log_progress(struct encryptGroupsData const* data, bool completed)
2377{
2378 // Precondition - if completed data = 0 else data != 0
2379
2380 // Track progress so we can skip logging blocks
2381 static off64_t offset = -1;
2382
2383 // Need to close existing 'Encrypting from' log?
2384 if (completed || (offset != -1 && data->offset != offset)) {
2385 SLOGI("Encrypted to sector %" PRId64,
2386 offset / info.block_size * CRYPT_SECTOR_SIZE);
2387 offset = -1;
2388 }
2389
2390 // Need to start new 'Encrypting from' log?
2391 if (!completed && offset != data->offset) {
2392 SLOGI("Encrypting from sector %" PRId64,
2393 data->offset / info.block_size * CRYPT_SECTOR_SIZE);
2394 }
2395
2396 // Update offset
2397 if (!completed) {
2398 offset = data->offset + (off64_t)data->count * info.block_size;
2399 }
2400}
2401
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002402static int flush_outstanding_data(struct encryptGroupsData* data)
2403{
David Ng5d636d42015-02-27 18:41:19 -08002404 static int64_t blocks_bufferred = 0;
2405
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002406 if (data->count == 0) {
2407 return 0;
2408 }
2409
Elliott Hughes231bdba2014-06-25 18:36:19 -07002410 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002411
2412 if (pread64(data->realfd, data->buffer,
2413 info.block_size * data->count, data->offset)
2414 <= 0) {
2415 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2416 data->real_blkdev);
2417 return -1;
2418 }
2419
2420 if (pwrite64(data->cryptofd, data->buffer,
2421 info.block_size * data->count, data->offset)
2422 <= 0) {
2423 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2424 data->crypto_blkdev);
2425 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002426 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002427 log_progress(data, false);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002428 }
2429
David Ng5d636d42015-02-27 18:41:19 -08002430 blocks_bufferred += data->count;
2431 if (blocks_bufferred >= BLOCKS_BEFORE_FLUSH) {
2432 fdatasync(data->cryptofd);
2433 blocks_bufferred = 0;
2434 }
2435
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002436 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002437 data->last_written_sector = (data->offset + data->count)
2438 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002439 return 0;
2440}
2441
2442static int encrypt_groups(struct encryptGroupsData* data)
2443{
2444 unsigned int i;
2445 u8 *block_bitmap = 0;
2446 unsigned int block;
2447 off64_t ret;
2448 int rc = -1;
2449
2450 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
2451 if (!data->buffer) {
2452 SLOGE("Failed to allocate crypto buffer");
2453 goto errout;
2454 }
2455
2456 block_bitmap = malloc(info.block_size);
2457 if (!block_bitmap) {
2458 SLOGE("failed to allocate block bitmap");
2459 goto errout;
2460 }
2461
2462 for (i = 0; i < aux_info.groups; ++i) {
2463 SLOGI("Encrypting group %d", i);
2464
2465 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2466 u32 block_count = min(info.blocks_per_group,
2467 aux_info.len_blocks - first_block);
2468
2469 off64_t offset = (u64)info.block_size
2470 * aux_info.bg_desc[i].bg_block_bitmap;
2471
2472 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2473 if (ret != (int)info.block_size) {
2474 SLOGE("failed to read all of block group bitmap %d", i);
2475 goto errout;
2476 }
2477
2478 offset = (u64)info.block_size * first_block;
2479
2480 data->count = 0;
2481
2482 for (block = 0; block < block_count; block++) {
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002483 int used = bitmap_get_bit(block_bitmap, block);
2484 update_progress(data, used);
2485 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002486 if (data->count == 0) {
2487 data->offset = offset;
2488 }
2489 data->count++;
2490 } else {
2491 if (flush_outstanding_data(data)) {
2492 goto errout;
2493 }
2494 }
2495
2496 offset += info.block_size;
2497
2498 /* Write data if we are aligned or buffer size reached */
2499 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2500 || data->count == BLOCKS_AT_A_TIME) {
2501 if (flush_outstanding_data(data)) {
2502 goto errout;
2503 }
2504 }
Paul Lawrence87999172014-02-20 12:21:31 -08002505
Paul Lawrence73d7a022014-06-09 14:10:09 -07002506 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002507 SLOGE("Stopping encryption due to low battery");
2508 rc = 0;
2509 goto errout;
2510 }
2511
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002512 }
2513 if (flush_outstanding_data(data)) {
2514 goto errout;
2515 }
2516 }
2517
Paul Lawrence87999172014-02-20 12:21:31 -08002518 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002519 rc = 0;
2520
2521errout:
Paul Lawrence3846be12014-09-22 11:33:54 -07002522 log_progress(0, true);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002523 free(data->buffer);
2524 free(block_bitmap);
2525 return rc;
2526}
2527
2528static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2529 char *real_blkdev,
2530 off64_t size,
2531 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002532 off64_t tot_size,
2533 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002534{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002535 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002536 struct encryptGroupsData data;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002537 int rc; // Can't initialize without causing warning -Wclobbered
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002538
Paul Lawrence87999172014-02-20 12:21:31 -08002539 if (previously_encrypted_upto > *size_already_done) {
2540 SLOGD("Not fast encrypting since resuming part way through");
2541 return -1;
2542 }
2543
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002544 memset(&data, 0, sizeof(data));
2545 data.real_blkdev = real_blkdev;
2546 data.crypto_blkdev = crypto_blkdev;
2547
2548 if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
JP Abgrall77768712014-10-10 15:52:11 -07002549 SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
2550 real_blkdev, errno, strerror(errno));
Paul Lawrence74f29f12014-08-28 15:54:10 -07002551 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002552 goto errout;
2553 }
2554
David Ng6564c0d2015-01-21 13:55:21 -08002555 // Wait until the block device appears. Re-use the mount retry values since it is reasonable.
2556 int retries = RETRY_MOUNT_ATTEMPTS;
2557 while ((data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
2558 if (--retries) {
2559 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s), retrying\n",
2560 crypto_blkdev, errno, strerror(errno));
2561 sleep(RETRY_MOUNT_DELAY_SECONDS);
2562 } else {
2563 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
2564 crypto_blkdev, errno, strerror(errno));
2565 rc = ENABLE_INPLACE_ERR_DEV;
2566 goto errout;
2567 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002568 }
2569
2570 if (setjmp(setjmp_env)) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002571 SLOGE("Reading ext4 extent caused an exception\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002572 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002573 goto errout;
2574 }
2575
2576 if (read_ext(data.realfd, 0) != 0) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002577 SLOGE("Failed to read ext4 extent\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002578 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002579 goto errout;
2580 }
2581
2582 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2583 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2584 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2585
JP Abgrall512f0d52014-10-10 18:43:41 -07002586 SLOGI("Encrypting ext4 filesystem in place...");
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002587
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002588 data.tot_used_blocks = data.numblocks;
2589 for (i = 0; i < aux_info.groups; ++i) {
2590 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2591 }
2592
2593 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002594 data.cur_pct = 0;
Paul Lawrence9c58a872014-09-30 09:12:51 -07002595
2596 struct timespec time_started = {0};
2597 if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
2598 SLOGW("Error getting time at start");
2599 // Note - continue anyway - we'll run with 0
2600 }
2601 data.time_started = time_started.tv_sec;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002602 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002603
2604 rc = encrypt_groups(&data);
2605 if (rc) {
2606 SLOGE("Error encrypting groups");
2607 goto errout;
2608 }
2609
Paul Lawrence87999172014-02-20 12:21:31 -08002610 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002611 rc = 0;
2612
2613errout:
2614 close(data.realfd);
2615 close(data.cryptofd);
2616
2617 return rc;
2618}
2619
Paul Lawrence3846be12014-09-22 11:33:54 -07002620static void log_progress_f2fs(u64 block, bool completed)
2621{
2622 // Precondition - if completed data = 0 else data != 0
2623
2624 // Track progress so we can skip logging blocks
2625 static u64 last_block = (u64)-1;
2626
2627 // Need to close existing 'Encrypting from' log?
2628 if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
2629 SLOGI("Encrypted to block %" PRId64, last_block);
2630 last_block = -1;
2631 }
2632
2633 // Need to start new 'Encrypting from' log?
2634 if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
2635 SLOGI("Encrypting from block %" PRId64, block);
2636 }
2637
2638 // Update offset
2639 if (!completed) {
2640 last_block = block;
2641 }
2642}
2643
Daniel Rosenberge82df162014-08-15 22:19:23 +00002644static int encrypt_one_block_f2fs(u64 pos, void *data)
2645{
2646 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2647
2648 priv_dat->blocks_already_done = pos - 1;
2649 update_progress(priv_dat, 1);
2650
2651 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2652
2653 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002654 SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002655 return -1;
2656 }
2657
2658 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002659 SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002660 return -1;
2661 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002662 log_progress_f2fs(pos, false);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002663 }
2664
2665 return 0;
2666}
2667
2668static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2669 char *real_blkdev,
2670 off64_t size,
2671 off64_t *size_already_done,
2672 off64_t tot_size,
2673 off64_t previously_encrypted_upto)
2674{
2675 u32 i;
2676 struct encryptGroupsData data;
2677 struct f2fs_info *f2fs_info = NULL;
JP Abgrall512f0d52014-10-10 18:43:41 -07002678 int rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002679 if (previously_encrypted_upto > *size_already_done) {
2680 SLOGD("Not fast encrypting since resuming part way through");
JP Abgrall512f0d52014-10-10 18:43:41 -07002681 return ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002682 }
2683 memset(&data, 0, sizeof(data));
2684 data.real_blkdev = real_blkdev;
2685 data.crypto_blkdev = crypto_blkdev;
2686 data.realfd = -1;
2687 data.cryptofd = -1;
2688 if ( (data.realfd = open64(real_blkdev, O_RDWR)) < 0) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002689 SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
Daniel Rosenberge82df162014-08-15 22:19:23 +00002690 real_blkdev);
2691 goto errout;
2692 }
2693 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002694 SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
JP Abgrall77768712014-10-10 15:52:11 -07002695 crypto_blkdev, errno, strerror(errno));
JP Abgrall512f0d52014-10-10 18:43:41 -07002696 rc = ENABLE_INPLACE_ERR_DEV;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002697 goto errout;
2698 }
2699
2700 f2fs_info = generate_f2fs_info(data.realfd);
2701 if (!f2fs_info)
2702 goto errout;
2703
2704 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2705 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2706 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2707
2708 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2709
2710 data.one_pct = data.tot_used_blocks / 100;
2711 data.cur_pct = 0;
2712 data.time_started = time(NULL);
2713 data.remaining_time = -1;
2714
2715 data.buffer = malloc(f2fs_info->block_size);
2716 if (!data.buffer) {
2717 SLOGE("Failed to allocate crypto buffer");
2718 goto errout;
2719 }
2720
2721 data.count = 0;
2722
2723 /* Currently, this either runs to completion, or hits a nonrecoverable error */
2724 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2725
2726 if (rc) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002727 SLOGE("Error in running over f2fs blocks");
2728 rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002729 goto errout;
2730 }
2731
2732 *size_already_done += size;
2733 rc = 0;
2734
2735errout:
2736 if (rc)
2737 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2738
Paul Lawrence3846be12014-09-22 11:33:54 -07002739 log_progress_f2fs(0, true);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002740 free(f2fs_info);
2741 free(data.buffer);
2742 close(data.realfd);
2743 close(data.cryptofd);
2744
2745 return rc;
2746}
2747
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002748static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2749 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002750 off64_t tot_size,
2751 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002752{
2753 int realfd, cryptofd;
2754 char *buf[CRYPT_INPLACE_BUFSIZE];
JP Abgrall512f0d52014-10-10 18:43:41 -07002755 int rc = ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002756 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002757 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002758 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002759
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002760 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
2761 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
JP Abgrall512f0d52014-10-10 18:43:41 -07002762 return ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002763 }
2764
2765 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall77768712014-10-10 15:52:11 -07002766 SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
2767 crypto_blkdev, errno, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002768 close(realfd);
JP Abgrall512f0d52014-10-10 18:43:41 -07002769 return ENABLE_INPLACE_ERR_DEV;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002770 }
2771
2772 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2773 * The size passed in is the number of 512 byte sectors in the filesystem.
2774 * So compute the number of whole 4K blocks we should read/write,
2775 * and the remainder.
2776 */
2777 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2778 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002779 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2780 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002781
2782 SLOGE("Encrypting filesystem in place...");
2783
Paul Lawrence87999172014-02-20 12:21:31 -08002784 i = previously_encrypted_upto + 1 - *size_already_done;
2785
2786 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2787 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2788 goto errout;
2789 }
2790
2791 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2792 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2793 goto errout;
2794 }
2795
2796 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2797 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2798 SLOGE("Error reading initial sectors from real_blkdev %s for "
2799 "inplace encrypt\n", crypto_blkdev);
2800 goto errout;
2801 }
2802 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2803 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2804 "inplace encrypt\n", crypto_blkdev);
2805 goto errout;
2806 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002807 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002808 }
2809 }
2810
Ken Sumrall29d8da82011-05-18 17:20:07 -07002811 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002812 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002813 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002814 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002815 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002816 if (new_pct > cur_pct) {
2817 char buf[8];
2818
2819 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002820 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002821 property_set("vold.encrypt_progress", buf);
2822 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002823 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002824 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002825 goto errout;
2826 }
2827 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002828 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2829 goto errout;
2830 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002831 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002832 CRYPT_SECTORS_PER_BUFSIZE,
2833 i * CRYPT_SECTORS_PER_BUFSIZE);
2834 }
2835
Paul Lawrence73d7a022014-06-09 14:10:09 -07002836 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002837 SLOGE("Stopping encryption due to low battery");
2838 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2839 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002840 goto errout;
2841 }
2842 }
2843
2844 /* Do any remaining sectors */
2845 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002846 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2847 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002848 goto errout;
2849 }
Paul Lawrence87999172014-02-20 12:21:31 -08002850 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2851 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002852 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002853 } else {
2854 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002855 }
2856 }
2857
Ken Sumrall29d8da82011-05-18 17:20:07 -07002858 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002859 rc = 0;
2860
2861errout:
2862 close(realfd);
2863 close(cryptofd);
2864
2865 return rc;
2866}
2867
JP Abgrall512f0d52014-10-10 18:43:41 -07002868/* returns on of the ENABLE_INPLACE_* return codes */
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002869static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2870 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002871 off64_t tot_size,
2872 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002873{
JP Abgrall512f0d52014-10-10 18:43:41 -07002874 int rc_ext4, rc_f2fs, rc_full;
Paul Lawrence87999172014-02-20 12:21:31 -08002875 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002876 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002877 }
2878
2879 if (*size_already_done + size < previously_encrypted_upto) {
2880 *size_already_done += size;
2881 return 0;
2882 }
2883
Daniel Rosenberge82df162014-08-15 22:19:23 +00002884 /* TODO: identify filesystem type.
2885 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2886 * then we will drop down to cryptfs_enable_inplace_f2fs.
2887 * */
JP Abgrall512f0d52014-10-10 18:43:41 -07002888 if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002889 size, size_already_done,
JP Abgrall512f0d52014-10-10 18:43:41 -07002890 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002891 return 0;
2892 }
JP Abgrall512f0d52014-10-10 18:43:41 -07002893 SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002894
JP Abgrall512f0d52014-10-10 18:43:41 -07002895 if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002896 size, size_already_done,
JP Abgrall512f0d52014-10-10 18:43:41 -07002897 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002898 return 0;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002899 }
JP Abgrall512f0d52014-10-10 18:43:41 -07002900 SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002901
JP Abgrall512f0d52014-10-10 18:43:41 -07002902 rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002903 size, size_already_done, tot_size,
2904 previously_encrypted_upto);
JP Abgrall512f0d52014-10-10 18:43:41 -07002905 SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
2906
2907 /* Hack for b/17898962, the following is the symptom... */
2908 if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
2909 && rc_f2fs == ENABLE_INPLACE_ERR_DEV
2910 && rc_full == ENABLE_INPLACE_ERR_DEV) {
2911 return ENABLE_INPLACE_ERR_DEV;
2912 }
2913 return rc_full;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002914}
2915
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002916#define CRYPTO_ENABLE_WIPE 1
2917#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002918
2919#define FRAMEWORK_BOOT_WAIT 60
2920
Ken Sumrall29d8da82011-05-18 17:20:07 -07002921static inline int should_encrypt(struct volume_info *volume)
2922{
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002923 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
Ken Sumrall29d8da82011-05-18 17:20:07 -07002924 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
2925}
2926
Paul Lawrence87999172014-02-20 12:21:31 -08002927static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2928{
2929 int fd = open(filename, O_RDONLY);
2930 if (fd == -1) {
2931 SLOGE("Error opening file %s", filename);
2932 return -1;
2933 }
2934
2935 char block[CRYPT_INPLACE_BUFSIZE];
2936 memset(block, 0, sizeof(block));
2937 if (unix_read(fd, block, sizeof(block)) < 0) {
2938 SLOGE("Error reading file %s", filename);
2939 close(fd);
2940 return -1;
2941 }
2942
2943 close(fd);
2944
2945 SHA256_CTX c;
2946 SHA256_Init(&c);
2947 SHA256_Update(&c, block, sizeof(block));
2948 SHA256_Final(buf, &c);
2949
2950 return 0;
2951}
2952
JP Abgrall62c7af32014-06-16 13:01:23 -07002953static int get_fs_type(struct fstab_rec *rec)
2954{
2955 if (!strcmp(rec->fs_type, "ext4")) {
2956 return EXT4_FS;
2957 } else if (!strcmp(rec->fs_type, "f2fs")) {
2958 return F2FS_FS;
2959 } else {
2960 return -1;
2961 }
2962}
2963
Paul Lawrence87999172014-02-20 12:21:31 -08002964static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2965 char *crypto_blkdev, char *real_blkdev,
2966 int previously_encrypted_upto)
2967{
2968 off64_t cur_encryption_done=0, tot_encryption_size=0;
2969 int i, rc = -1;
2970
Paul Lawrence73d7a022014-06-09 14:10:09 -07002971 if (!is_battery_ok_to_start()) {
2972 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002973 return 0;
2974 }
2975
2976 /* The size of the userdata partition, and add in the vold volumes below */
2977 tot_encryption_size = crypt_ftr->fs_size;
2978
2979 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002980 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2981 int fs_type = get_fs_type(rec);
2982 if (fs_type < 0) {
2983 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2984 return -1;
2985 }
2986 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002987 } else if (how == CRYPTO_ENABLE_INPLACE) {
2988 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2989 crypt_ftr->fs_size, &cur_encryption_done,
2990 tot_encryption_size,
2991 previously_encrypted_upto);
2992
JP Abgrall512f0d52014-10-10 18:43:41 -07002993 if (rc == ENABLE_INPLACE_ERR_DEV) {
2994 /* Hack for b/17898962 */
2995 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2996 cryptfs_reboot(reboot);
2997 }
2998
Paul Lawrence73d7a022014-06-09 14:10:09 -07002999 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08003000 crypt_ftr->encrypted_upto = cur_encryption_done;
3001 }
3002
Paul Lawrence73d7a022014-06-09 14:10:09 -07003003 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003004 /* The inplace routine never actually sets the progress to 100% due
3005 * to the round down nature of integer division, so set it here */
3006 property_set("vold.encrypt_progress", "100");
3007 }
3008 } else {
3009 /* Shouldn't happen */
3010 SLOGE("cryptfs_enable: internal error, unknown option\n");
3011 rc = -1;
3012 }
3013
3014 return rc;
3015}
3016
Paul Lawrence13486032014-02-03 13:28:11 -08003017int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
3018 int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003019{
3020 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08003021 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07003022 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003023 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07003024 int rc=-1, fd, i, ret;
Paul Lawrence87999172014-02-20 12:21:31 -08003025 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003026 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003027 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003028 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07003029 char key_loc[PROPERTY_VALUE_MAX];
3030 char fuse_sdcard[PROPERTY_VALUE_MAX];
3031 char *sd_mnt_point;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003032 int num_vols;
3033 struct volume_info *vol_list = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08003034 off64_t previously_encrypted_upto = 0;
Dinesh K Gargdb2b1ed2014-10-08 16:20:03 -07003035#ifdef CONFIG_HW_DISK_ENCRYPTION
3036 int key_index = 0;
3037#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07003038
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003039 if (!strcmp(howarg, "wipe")) {
3040 how = CRYPTO_ENABLE_WIPE;
3041 } else if (! strcmp(howarg, "inplace")) {
3042 how = CRYPTO_ENABLE_INPLACE;
3043 } else {
3044 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08003045 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003046 }
3047
Paul Lawrence87999172014-02-20 12:21:31 -08003048 /* See if an encryption was underway and interrupted */
3049 if (how == CRYPTO_ENABLE_INPLACE
3050 && get_crypt_ftr_and_key(&crypt_ftr) == 0
3051 && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
3052 previously_encrypted_upto = crypt_ftr.encrypted_upto;
3053 crypt_ftr.encrypted_upto = 0;
Paul Lawrence6bfed202014-07-28 12:47:22 -07003054 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
3055
3056 /* At this point, we are in an inconsistent state. Until we successfully
3057 complete encryption, a reboot will leave us broken. So mark the
3058 encryption failed in case that happens.
3059 On successfully completing encryption, remove this flag */
3060 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
3061
3062 put_crypt_ftr_and_key(&crypt_ftr);
Paul Lawrence87999172014-02-20 12:21:31 -08003063 }
3064
3065 property_get("ro.crypto.state", encrypted_state, "");
3066 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
3067 SLOGE("Device is already running encrypted, aborting");
3068 goto error_unencrypted;
3069 }
3070
3071 // TODO refactor fs_mgr_get_crypt_info to get both in one call
3072 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08003073 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003074
Ken Sumrall3ed82362011-01-28 23:31:16 -08003075 /* Get the size of the real block device */
3076 fd = open(real_blkdev, O_RDONLY);
3077 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
3078 SLOGE("Cannot get size of block device %s\n", real_blkdev);
3079 goto error_unencrypted;
3080 }
3081 close(fd);
3082
3083 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003084 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003085 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00003086 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00003087 if (fs_size_sec == 0)
3088 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
3089
Paul Lawrence87999172014-02-20 12:21:31 -08003090 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003091
3092 if (fs_size_sec > max_fs_size_sec) {
3093 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
3094 goto error_unencrypted;
3095 }
3096 }
3097
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003098 /* Get a wakelock as this may take a while, and we don't want the
3099 * device to sleep on us. We'll grab a partial wakelock, and if the UI
3100 * wants to keep the screen on, it can grab a full wakelock.
3101 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003102 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003103 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
3104
Jeff Sharkey7382f812012-08-23 14:08:59 -07003105 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07003106 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07003107 if (!sd_mnt_point) {
3108 sd_mnt_point = getenv("EXTERNAL_STORAGE");
3109 }
3110 if (!sd_mnt_point) {
3111 sd_mnt_point = "/mnt/sdcard";
3112 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07003113
Paul Lawrence87999172014-02-20 12:21:31 -08003114 /* TODO
3115 * Currently do not have test devices with multiple encryptable volumes.
3116 * When we acquire some, re-add support.
3117 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003118 num_vols=vold_getNumDirectVolumes();
3119 vol_list = malloc(sizeof(struct volume_info) * num_vols);
3120 vold_getDirectVolumeList(vol_list);
3121
3122 for (i=0; i<num_vols; i++) {
3123 if (should_encrypt(&vol_list[i])) {
Paul Lawrence87999172014-02-20 12:21:31 -08003124 SLOGE("Cannot encrypt if there are multiple encryptable volumes"
3125 "%s\n", vol_list[i].label);
3126 goto error_unencrypted;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003127 }
3128 }
3129
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003130 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003131 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003132 */
3133 property_set("vold.decrypt", "trigger_shutdown_framework");
3134 SLOGD("Just asked init to shut down class main\n");
3135
Ken Sumrall425524d2012-06-14 20:55:28 -07003136 if (vold_unmountAllAsecs()) {
3137 /* Just report the error. If any are left mounted,
3138 * umounting /data below will fail and handle the error.
3139 */
3140 SLOGE("Error unmounting internal asecs");
3141 }
3142
Ken Sumrall29d8da82011-05-18 17:20:07 -07003143 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
3144 if (!strcmp(fuse_sdcard, "true")) {
3145 /* This is a device using the fuse layer to emulate the sdcard semantics
3146 * on top of the userdata partition. vold does not manage it, it is managed
3147 * by the sdcard service. The sdcard service was killed by the property trigger
3148 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
3149 * unlike the case for vold managed devices above.
3150 */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07003151 if (wait_and_unmount(sd_mnt_point, false)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07003152 goto error_shutting_down;
3153 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08003154 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003155
3156 /* Now unmount the /data partition. */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07003157 if (wait_and_unmount(DATA_MNT_POINT, false)) {
JP Abgrall502dc742013-11-01 13:06:20 -07003158 if (allow_reboot) {
3159 goto error_shutting_down;
3160 } else {
3161 goto error_unencrypted;
3162 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003163 }
3164
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003165 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003166 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence87999172014-02-20 12:21:31 -08003167 if (previously_encrypted_upto == 0) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07003168 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
3169 goto error_shutting_down;
3170 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003171
Paul Lawrence87999172014-02-20 12:21:31 -08003172 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
3173 crypt_ftr.fs_size = nr_sec
3174 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
3175 } else {
3176 crypt_ftr.fs_size = nr_sec;
3177 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07003178 /* At this point, we are in an inconsistent state. Until we successfully
3179 complete encryption, a reboot will leave us broken. So mark the
3180 encryption failed in case that happens.
3181 On successfully completing encryption, remove this flag */
3182 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence87999172014-02-20 12:21:31 -08003183 crypt_ftr.crypt_type = crypt_type;
Dinesh K Gargf58801b2014-01-13 14:16:47 -08003184#ifndef CONFIG_HW_DISK_ENCRYPTION
3185 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
3186#else
3187 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-xts", MAX_CRYPTO_TYPE_NAME_LEN);
AnilKumar Chimata4e5db572014-11-19 16:39:40 -08003188 wipe_hw_device_encryption_key((char*)crypt_ftr.crypto_type_name);
Dinesh K Gargdb2b1ed2014-10-08 16:20:03 -07003189 key_index = set_hw_device_encryption_key(passwd, (char*)crypt_ftr.crypto_type_name);
3190 if (key_index < 0)
Dinesh K Gargf58801b2014-01-13 14:16:47 -08003191 goto error_shutting_down;
3192#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003193
Paul Lawrence87999172014-02-20 12:21:31 -08003194 /* Make an encrypted master key */
3195 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
3196 SLOGE("Cannot create encrypted master key\n");
3197 goto error_shutting_down;
3198 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003199
Paul Lawrence87999172014-02-20 12:21:31 -08003200 /* Write the key to the end of the partition */
3201 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003202
Paul Lawrence87999172014-02-20 12:21:31 -08003203 /* If any persistent data has been remembered, save it.
3204 * If none, create a valid empty table and save that.
3205 */
3206 if (!persist_data) {
3207 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
3208 if (pdata) {
3209 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
3210 persist_data = pdata;
3211 }
3212 }
3213 if (persist_data) {
3214 save_persistent_data();
3215 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003216 }
3217
Dinesh K Garg7a556382014-09-11 11:09:24 -07003218 /* Do extra work for a better UX when doing the long inplace encryption */
3219 if (how == CRYPTO_ENABLE_INPLACE) {
3220 /* Now that /data is unmounted, we need to mount a tmpfs
3221 * /data, set a property saying we're doing inplace encryption,
3222 * and restart the framework.
3223 */
3224 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
3225 goto error_shutting_down;
3226 }
3227 /* Tells the framework that inplace encryption is starting */
3228 property_set("vold.encrypt_progress", "0");
3229
3230 /* restart the framework. */
3231 /* Create necessary paths on /data */
3232 if (prep_data_fs()) {
3233 goto error_shutting_down;
3234 }
3235
3236 /* Ugh, shutting down the framework is not synchronous, so until it
3237 * can be fixed, this horrible hack will wait a moment for it all to
3238 * shut down before proceeding. Without it, some devices cannot
3239 * restart the graphics services.
3240 */
3241 sleep(2);
3242
3243 /* startup service classes main and late_start */
3244 property_set("vold.decrypt", "trigger_restart_min_framework");
3245 SLOGD("Just triggered restart_min_framework\n");
3246
3247 /* OK, the framework is restarted and will soon be showing a
3248 * progress bar. Time to setup an encrypted mapping, and
3249 * either write a new filesystem, or encrypt in place updating
3250 * the progress bar as we work.
3251 */
3252 }
3253
Paul Lawrenced0c7b172014-08-08 14:28:10 -07003254 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Dinesh K Gargdb2b1ed2014-10-08 16:20:03 -07003255#ifdef CONFIG_HW_DISK_ENCRYPTION
3256 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name) && is_ice_enabled())
3257 create_crypto_blk_dev(&crypt_ftr, &key_index, real_blkdev, crypto_blkdev,
3258 "userdata");
3259 else
3260 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
3261 "userdata");
3262
3263#else
Ken Sumrall29d8da82011-05-18 17:20:07 -07003264 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
3265 "userdata");
Dinesh K Gargdb2b1ed2014-10-08 16:20:03 -07003266#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07003267
Paul Lawrence87999172014-02-20 12:21:31 -08003268 /* If we are continuing, check checksums match */
3269 rc = 0;
3270 if (previously_encrypted_upto) {
3271 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
3272 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07003273
Paul Lawrence87999172014-02-20 12:21:31 -08003274 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
3275 sizeof(hash_first_block)) != 0) {
3276 SLOGE("Checksums do not match - trigger wipe");
3277 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003278 }
3279 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003280
Paul Lawrence87999172014-02-20 12:21:31 -08003281 if (!rc) {
3282 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
3283 crypto_blkdev, real_blkdev,
3284 previously_encrypted_upto);
3285 }
3286
3287 /* Calculate checksum if we are not finished */
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003288 if (!rc && how == CRYPTO_ENABLE_INPLACE
3289 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003290 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
3291 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07003292 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08003293 SLOGE("Error calculating checksum for continuing encryption");
3294 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003295 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003296 }
3297
3298 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003299 delete_crypto_blk_dev("userdata");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003300
3301 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003302
3303 if (! rc) {
3304 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003305 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08003306
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003307 if (how == CRYPTO_ENABLE_INPLACE
3308 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003309 SLOGD("Encrypted up to sector %lld - will continue after reboot",
3310 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07003311 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08003312 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07003313
Divya Sharma6f00a4a2014-09-07 09:26:38 +03003314 if (how == CRYPTO_ENABLE_INPLACE)
3315 crypt_ftr.flags |= CRYPT_FDE_COMPLETED;
Paul Lawrence6bfed202014-07-28 12:47:22 -07003316 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08003317
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003318 if (how == CRYPTO_ENABLE_WIPE
3319 || crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003320 char value[PROPERTY_VALUE_MAX];
3321 property_get("ro.crypto.state", value, "");
3322 if (!strcmp(value, "")) {
3323 /* default encryption - continue first boot sequence */
3324 property_set("ro.crypto.state", "encrypted");
3325 release_wake_lock(lockid);
3326 cryptfs_check_passwd(DEFAULT_PASSWORD);
3327 cryptfs_restart_internal(1);
3328 return 0;
3329 } else {
3330 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08003331 cryptfs_reboot(reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003332 }
Paul Lawrence87999172014-02-20 12:21:31 -08003333 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003334 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Paul Lawrence87999172014-02-20 12:21:31 -08003335 cryptfs_reboot(shutdown);
3336 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003337 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003338 char value[PROPERTY_VALUE_MAX];
3339
Ken Sumrall319369a2012-06-27 16:30:18 -07003340 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003341 if (!strcmp(value, "1")) {
3342 /* wipe data if encryption failed */
3343 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
3344 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07003345 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003346 if (fd >= 0) {
Jeff Sharkeydd1a8042014-09-24 11:46:51 -07003347 write(fd, "--wipe_data\n", strlen("--wipe_data\n") + 1);
3348 write(fd, "--reason=cryptfs_enable_internal\n", strlen("--reason=cryptfs_enable_internal\n") + 1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003349 close(fd);
3350 } else {
3351 SLOGE("could not open /cache/recovery/command\n");
3352 }
Paul Lawrence87999172014-02-20 12:21:31 -08003353 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003354 } else {
3355 /* set property to trigger dialog */
3356 property_set("vold.encrypt_progress", "error_partially_encrypted");
3357 release_wake_lock(lockid);
3358 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003359 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003360 }
3361
Ken Sumrall3ed82362011-01-28 23:31:16 -08003362 /* hrm, the encrypt step claims success, but the reboot failed.
3363 * This should not happen.
3364 * Set the property and return. Hope the framework can deal with it.
3365 */
3366 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003367 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003368 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08003369
3370error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07003371 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003372 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003373 if (lockid[0]) {
3374 release_wake_lock(lockid);
3375 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003376 return -1;
3377
3378error_shutting_down:
3379 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3380 * but the framework is stopped and not restarted to show the error, so it's up to
3381 * vold to restart the system.
3382 */
3383 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08003384 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003385
3386 /* shouldn't get here */
3387 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003388 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003389 if (lockid[0]) {
3390 release_wake_lock(lockid);
3391 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003392 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003393}
3394
Divya Sharma6f00a4a2014-09-07 09:26:38 +03003395/**
3396 * Map /data to dm-req-crypt upon PFE Activation.
3397 *
3398 * The UI framework needs to be shut-down and restart.
3399 *
3400 * based on cryptfs_enable() + cryptfs_restart()
3401 */
3402int cryptfs_pfe_activate(void)
3403{
3404 char crypto_blkdev[MAXPATHLEN];
3405 char real_blkdev[MAXPATHLEN];
3406 unsigned long nr_sec;
3407 unsigned char decrypted_master_key[KEY_LEN_BYTES] = {0}; /* N.A */
3408 int rc = -1;
3409 int fd = -1; /* real_blkdev file descriptor */
3410 struct crypt_mnt_ftr crypt_ftr = {0};
3411 char encrypted_state[PROPERTY_VALUE_MAX] = {0};
3412 char pfe_state[PROPERTY_VALUE_MAX] = {0};
3413 char lockid[32] = { 0};
3414 char key_loc[PROPERTY_VALUE_MAX] = {0};
3415 int retry = 5; /* mount retry, /data might be hold by services going down */
3416
3417 SLOGI("Start PFE mapping upon activation..");
3418
3419 property_get("vold.pfe", pfe_state, "");
3420 if (!strcmp(pfe_state, "activated") ) {
3421 SLOGI("PFE already activated!");
3422 return 0;
3423 }
3424
3425 /* If FDE actiavted, no mapping required, just set a flag in the footer */
3426 property_get("ro.crypto.state", encrypted_state, "");
3427 if (strcmp(encrypted_state, "encrypted") == 0) {
3428 SLOGI("FDE activated , no need to map crypto-device");
3429
3430 /* get the footer */
3431 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3432 SLOGE("Error getting crypt footer");
3433 return -1;
3434 }
3435
3436 /* Set PFE flag */
3437 crypt_ftr.flags |= CRYPT_PFE_ACTIVATED;
3438
3439 /* save the flag in the footer */
3440 if (put_crypt_ftr_and_key(&crypt_ftr)) {
3441 SLOGE("Error saving crypt footer");
3442 return -1;
3443 }
3444
3445 property_set("vold.pfe", "activated");
3446 SLOGI("%s: PFE-Enable (after FDE) completed OK", __func__);
3447
3448 return 0;
3449 }
3450
3451 property_set("vold.pfe", ""); /* reset prop */
3452
3453 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
3454
3455 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
3456
3457 /* Get the size of the real block device */
3458 fd = open(real_blkdev, O_RDONLY);
3459 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
3460 SLOGE("Cannot get size of block device %s", real_blkdev);
3461 goto get_size_error;
3462 }
3463 close(fd);
3464
3465 /* Get a wakelock as this may take a while, and we don't want the
3466 * device to sleep on us. We'll grab a partial wakelock, and if the UI
3467 * wants to keep the screen on, it can grab a full wakelock.
3468 */
3469 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
3470 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
3471
3472 /* Allow caller to get response */
3473 sleep(1);
3474
3475 /* The init files are setup to stop the class main and late start when
3476 * vold sets trigger_shutdown_framework.
3477 */
3478 property_set("vold.decrypt", "trigger_shutdown_framework");
3479 SLOGI("Just asked init to shut down class main");
3480
3481 if (vold_unmountAllAsecs()) {
3482 /* Just report the error. If any are left mounted,
3483 * umounting /data below will fail and handle the error.
3484 */
3485 SLOGE("Error unmounting internal asecs");
3486 }
3487
3488 /* Now unmount the /data partition. */
Chiou-Hao Hsue7236f82014-10-09 18:55:50 -07003489 if (wait_and_unmount(DATA_MNT_POINT, false)) {
Divya Sharma6f00a4a2014-09-07 09:26:38 +03003490 SLOGE("%s: Unmount /data failed", __func__);
3491 goto unmount_error;
3492 }
3493
3494 /* Start the actual work of making an encrypted filesystem */
3495 /* Initialize a crypt_mnt_ftr for the partition */
3496 cryptfs_init_crypt_mnt_ftr(&crypt_ftr);
3497
3498 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
3499 SLOGI("Use fs_size from footer");
3500 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
3501 } else {
3502 SLOGI("Use fs_size from get-blk-size");
3503 crypt_ftr.fs_size = nr_sec;
3504 }
3505
3506 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-xts", MAX_CRYPTO_TYPE_NAME_LEN);
3507
3508 rc = create_crypto_blk_dev(&crypt_ftr, decrypted_master_key,
3509 real_blkdev, crypto_blkdev, "userdata");
3510 if (rc) {
3511 SLOGE("%s: Create crypto block-device failed !", __func__);
3512 goto mapping_err;
3513 }
3514
3515 sleep(1); // Sleep before mount
3516
3517 /* If that succeeded, then mount the decrypted filesystem */
3518 while (retry) {
3519 rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, 0);
3520 if (rc) {
3521 SLOGE("%s: Mount /data to crypto device FAILED !", __func__);
3522 if (retry == 0) {
3523 goto mapping_err;
3524 }
3525 } else {
3526 SLOGI("%s: Mount /data to crypto device OK !", __func__);
3527 break;
3528 }
3529 retry--;
3530 sleep(3); // Sleep few seconds before retry
3531 }
3532
3533 property_set("vold.decrypt", "trigger_load_persist_props");
3534 /* Create necessary paths on /data */
3535 if (prep_data_fs()) {
3536 SLOGE("%s: prep_data_fs() FAILED !", __func__);
3537 goto mapping_err;
3538 }
3539
3540 /* startup service classes main and late_start */
3541 property_set("vold.decrypt", "trigger_restart_framework");
3542 SLOGI("Just triggered restart_framework");
3543
3544 /* Give it a few moments to get started */
3545 sleep(1);
3546
3547 release_wake_lock(lockid);
3548
3549 crypt_ftr.flags |= CRYPT_PFE_ACTIVATED;
3550
3551 /* Write the footer with flag activated */
3552 put_crypt_ftr_and_key(&crypt_ftr);
3553
3554 property_set("vold.pfe", "activated");
3555
3556 SLOGI("%s: PFE-Enable (no FDE) completed OK", __func__);
3557 return 0;
3558
3559error_shutting_down:
3560mapping_err:
3561 delete_crypto_blk_dev("userdata");
3562error_unencrypted:
3563random_key_error:
3564unmount_error:
3565 release_wake_lock(lockid);
3566get_size_error:
3567 property_set("vold.pfe", "failed");
3568 SLOGI("%s: PFE Enable Failed", __func__);
3569
3570 return -1;
3571}
3572
3573/* Clear PFE activated flag. */
3574int cryptfs_pfe_deactivate(void)
3575{
3576 struct crypt_mnt_ftr crypt_ftr;
3577
3578 SLOGI("Start cryptfs_pfe_deactivate");
3579
3580 /* get the footer */
3581 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3582 SLOGE("Error getting crypt footer");
3583 return -1;
3584 }
3585
3586 /* clear the flag */
3587 crypt_ftr.flags &= ~CRYPT_PFE_ACTIVATED;
3588
3589 /* save the footer */
3590 if (put_crypt_ftr_and_key(&crypt_ftr)) {
3591 SLOGE("Error saving crypt footer");
3592 return -1;
3593 }
3594
3595 property_set("vold.pfe", "deactivated");
3596
3597 return 0;
3598}
3599
3600/*
3601 * Mount /data to dm-req-crypt on BOOT (if activated), same as after FDE.
3602 *
3603 * Note: After FDE is encrypted, the following commands are called on boot:
3604 * 1. cryptocomplete -> cryptfs_crypto_complete()
3605 * 2. checkpw -> cryptfs_check_passwd()
3606 * 3. restart -> cryptfs_restart()
3607 *
3608 * see test_mount_encrypted_fs()
3609 */
3610int cryptfs_pfe_boot(void)
3611{
3612 struct crypt_mnt_ftr crypt_ftr = {0};
3613
3614 SLOGI("Check if PFE is activated on Boot");
3615
3616 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3617 SLOGE("Error getting crypt footer and key");
3618 goto exit_err;
3619 }
3620
3621 if (!(crypt_ftr.flags & CRYPT_PFE_ACTIVATED) ) {
3622 SLOGE("PFE not activated");
3623 goto exit_err;
3624 }
3625
3626 if (crypt_ftr.flags & CRYPT_FDE_COMPLETED) {
3627 SLOGI("FDE Completed , let FDE do the crypto mount");
3628 goto exit_err;
3629 }
3630
3631 /* Mount /data , same as on activate command */
3632 return cryptfs_pfe_activate();
3633
3634exit_err:
3635 property_set("vold.pfe", "deactivated"); /* Default */
3636 return -1;
3637}
3638
Paul Lawrence45f10532014-04-04 18:11:56 +00003639int cryptfs_enable(char *howarg, int type, char *passwd, int allow_reboot)
Paul Lawrence13486032014-02-03 13:28:11 -08003640{
Paul Lawrencefc615042014-10-04 15:32:29 -07003641 char* adjusted_passwd = adjust_passwd(passwd);
3642 if (adjusted_passwd) {
3643 passwd = adjusted_passwd;
3644 }
3645
3646 int rc = cryptfs_enable_internal(howarg, type, passwd, allow_reboot);
3647
3648 free(adjusted_passwd);
3649 return rc;
Paul Lawrence13486032014-02-03 13:28:11 -08003650}
3651
3652int cryptfs_enable_default(char *howarg, int allow_reboot)
3653{
3654 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
3655 DEFAULT_PASSWORD, allow_reboot);
3656}
3657
3658int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003659{
3660 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003661 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003662
3663 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003664 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003665 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003666 return -1;
3667 }
3668
Paul Lawrencef4faa572014-01-29 13:31:03 -08003669 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3670 SLOGE("Invalid crypt_type %d", crypt_type);
3671 return -1;
3672 }
3673
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003674 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003675 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003676 SLOGE("Error getting crypt footer and key");
3677 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003678 }
3679
Paul Lawrencef4faa572014-01-29 13:31:03 -08003680 crypt_ftr.crypt_type = crypt_type;
3681
Paul Lawrencefc615042014-10-04 15:32:29 -07003682 char* adjusted_passwd = adjust_passwd(newpw);
3683 if (adjusted_passwd) {
3684 newpw = adjusted_passwd;
3685 }
3686
Paul Lawrencef4faa572014-01-29 13:31:03 -08003687 encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
3688 : newpw,
3689 crypt_ftr.salt,
3690 saved_master_key,
3691 crypt_ftr.master_key,
3692 &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003693
Jason parks70a4b3f2011-01-28 10:10:47 -06003694 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003695 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003696
Paul Lawrencefc615042014-10-04 15:32:29 -07003697 free(adjusted_passwd);
Ajay Dudani87701e22014-09-17 21:02:52 -07003698
Dinesh K Gargf58801b2014-01-13 14:16:47 -08003699#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08003700 if (!strcmp((char *)crypt_ftr.crypto_type_name, "aes-xts")) {
3701 if (crypt_type == CRYPT_TYPE_DEFAULT) {
3702 int rc = update_hw_device_encryption_key(DEFAULT_PASSWORD, (char*) crypt_ftr.crypto_type_name);
3703 SLOGD("Update hardware encryption key to default for crypt_type: %d. rc = %d", crypt_type, rc);
3704 if (!rc)
3705 return -1;
3706 } else {
3707 int rc = update_hw_device_encryption_key(newpw, (char*) crypt_ftr.crypto_type_name);
3708 SLOGD("Update hardware encryption key for crypt_type: %d. rc = %d", crypt_type, rc);
3709 if (!rc)
3710 return -1;
3711 }
Ajay Dudani87701e22014-09-17 21:02:52 -07003712 }
Dinesh K Gargf58801b2014-01-13 14:16:47 -08003713#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003714 return 0;
3715}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003716
Rubin Xu85c01f92014-10-13 12:49:54 +01003717static unsigned int persist_get_max_entries(int encrypted) {
3718 struct crypt_mnt_ftr crypt_ftr;
3719 unsigned int dsize;
3720 unsigned int max_persistent_entries;
3721
3722 /* If encrypted, use the values from the crypt_ftr, otherwise
3723 * use the values for the current spec.
3724 */
3725 if (encrypted) {
3726 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3727 return -1;
3728 }
3729 dsize = crypt_ftr.persist_data_size;
3730 } else {
3731 dsize = CRYPT_PERSIST_DATA_SIZE;
3732 }
3733
3734 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3735 sizeof(struct crypt_persist_entry);
3736
3737 return max_persistent_entries;
3738}
3739
3740static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003741{
3742 unsigned int i;
3743
3744 if (persist_data == NULL) {
3745 return -1;
3746 }
3747 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3748 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3749 /* We found it! */
3750 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3751 return 0;
3752 }
3753 }
3754
3755 return -1;
3756}
3757
Rubin Xu85c01f92014-10-13 12:49:54 +01003758static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003759{
3760 unsigned int i;
3761 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003762 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003763
3764 if (persist_data == NULL) {
3765 return -1;
3766 }
3767
Rubin Xu85c01f92014-10-13 12:49:54 +01003768 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003769
3770 num = persist_data->persist_valid_entries;
3771
3772 for (i = 0; i < num; i++) {
3773 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3774 /* We found an existing entry, update it! */
3775 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3776 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3777 return 0;
3778 }
3779 }
3780
3781 /* We didn't find it, add it to the end, if there is room */
3782 if (persist_data->persist_valid_entries < max_persistent_entries) {
3783 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3784 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3785 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3786 persist_data->persist_valid_entries++;
3787 return 0;
3788 }
3789
3790 return -1;
3791}
3792
Rubin Xu85c01f92014-10-13 12:49:54 +01003793/**
3794 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3795 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3796 */
3797static int match_multi_entry(const char *key, const char *field, unsigned index) {
3798 unsigned int i;
3799 unsigned int field_len;
3800 unsigned int key_index;
3801 field_len = strlen(field);
3802
3803 if (index == 0) {
3804 // The first key in a multi-entry field is just the filedname itself.
3805 if (!strcmp(key, field)) {
3806 return 1;
3807 }
3808 }
3809 // Match key against "%s_%d" % (field, index)
3810 if (strlen(key) < field_len + 1 + 1) {
3811 // Need at least a '_' and a digit.
3812 return 0;
3813 }
3814 if (strncmp(key, field, field_len)) {
3815 // If the key does not begin with field, it's not a match.
3816 return 0;
3817 }
3818 if (1 != sscanf(&key[field_len],"_%d", &key_index)) {
3819 return 0;
3820 }
3821 return key_index >= index;
3822}
3823
3824/*
3825 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3826 * remaining entries starting from index will be deleted.
3827 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3828 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3829 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3830 *
3831 */
3832static int persist_del_keys(const char *fieldname, unsigned index)
3833{
3834 unsigned int i;
3835 unsigned int j;
3836 unsigned int num;
3837
3838 if (persist_data == NULL) {
3839 return PERSIST_DEL_KEY_ERROR_OTHER;
3840 }
3841
3842 num = persist_data->persist_valid_entries;
3843
3844 j = 0; // points to the end of non-deleted entries.
3845 // Filter out to-be-deleted entries in place.
3846 for (i = 0; i < num; i++) {
3847 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3848 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3849 j++;
3850 }
3851 }
3852
3853 if (j < num) {
3854 persist_data->persist_valid_entries = j;
3855 // Zeroise the remaining entries
3856 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3857 return PERSIST_DEL_KEY_OK;
3858 } else {
3859 // Did not find an entry matching the given fieldname
3860 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3861 }
3862}
3863
3864static int persist_count_keys(const char *fieldname)
3865{
3866 unsigned int i;
3867 unsigned int count;
3868
3869 if (persist_data == NULL) {
3870 return -1;
3871 }
3872
3873 count = 0;
3874 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3875 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3876 count++;
3877 }
3878 }
3879
3880 return count;
3881}
3882
Ken Sumrall160b4d62013-04-22 12:15:39 -07003883/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003884int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003885{
3886 char temp_value[PROPERTY_VALUE_MAX];
3887 char real_blkdev[MAXPATHLEN];
Rubin Xu85c01f92014-10-13 12:49:54 +01003888 /* CRYPTO_GETFIELD_OK is success,
3889 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3890 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3891 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003892 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003893 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3894 int i;
3895 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003896
3897 if (persist_data == NULL) {
3898 load_persistent_data();
3899 if (persist_data == NULL) {
3900 SLOGE("Getfield error, cannot load persistent data");
3901 goto out;
3902 }
3903 }
3904
Rubin Xu85c01f92014-10-13 12:49:54 +01003905 // Read value from persistent entries. If the original value is split into multiple entries,
3906 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003907 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003908 // We found it, copy it to the caller's buffer and keep going until all entries are read.
3909 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
3910 // value too small
3911 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3912 goto out;
3913 }
3914 rc = CRYPTO_GETFIELD_OK;
3915
3916 for (i = 1; /* break explicitly */; i++) {
3917 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
3918 (int) sizeof(temp_field)) {
3919 // If the fieldname is very long, we stop as soon as it begins to overflow the
3920 // maximum field length. At this point we have in fact fully read out the original
3921 // value because cryptfs_setfield would not allow fields with longer names to be
3922 // written in the first place.
3923 break;
3924 }
3925 if (!persist_get_key(temp_field, temp_value)) {
3926 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3927 // value too small.
3928 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3929 goto out;
3930 }
3931 } else {
3932 // Exhaust all entries.
3933 break;
3934 }
3935 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003936 } else {
3937 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003938 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003939 }
3940
3941out:
3942 return rc;
3943}
3944
3945/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003946int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003947{
3948 struct crypt_persist_data stored_pdata;
3949 struct crypt_persist_data *pdata_p;
3950 struct crypt_mnt_ftr crypt_ftr;
3951 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003952 /* 0 is success, negative values are error */
3953 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003954 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003955 unsigned int field_id;
3956 char temp_field[PROPERTY_KEY_MAX];
3957 unsigned int num_entries;
3958 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003959
3960 if (persist_data == NULL) {
3961 load_persistent_data();
3962 if (persist_data == NULL) {
3963 SLOGE("Setfield error, cannot load persistent data");
3964 goto out;
3965 }
3966 }
3967
3968 property_get("ro.crypto.state", encrypted_state, "");
3969 if (!strcmp(encrypted_state, "encrypted") ) {
3970 encrypted = 1;
3971 }
3972
Rubin Xu85c01f92014-10-13 12:49:54 +01003973 // Compute the number of entries required to store value, each entry can store up to
3974 // (PROPERTY_VALUE_MAX - 1) chars
3975 if (strlen(value) == 0) {
3976 // Empty value also needs one entry to store.
3977 num_entries = 1;
3978 } else {
3979 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3980 }
3981
3982 max_keylen = strlen(fieldname);
3983 if (num_entries > 1) {
3984 // Need an extra "_%d" suffix.
3985 max_keylen += 1 + log10(num_entries);
3986 }
3987 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3988 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003989 goto out;
3990 }
3991
Rubin Xu85c01f92014-10-13 12:49:54 +01003992 // Make sure we have enough space to write the new value
3993 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3994 persist_get_max_entries(encrypted)) {
3995 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3996 goto out;
3997 }
3998
3999 // Now that we know persist_data has enough space for value, let's delete the old field first
4000 // to make up space.
4001 persist_del_keys(fieldname, 0);
4002
4003 if (persist_set_key(fieldname, value, encrypted)) {
4004 // fail to set key, should not happen as we have already checked the available space
4005 SLOGE("persist_set_key() error during setfield()");
4006 goto out;
4007 }
4008
4009 for (field_id = 1; field_id < num_entries; field_id++) {
4010 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
4011
4012 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
4013 // fail to set key, should not happen as we have already checked the available space.
4014 SLOGE("persist_set_key() error during setfield()");
4015 goto out;
4016 }
4017 }
4018
Ken Sumrall160b4d62013-04-22 12:15:39 -07004019 /* If we are running encrypted, save the persistent data now */
4020 if (encrypted) {
4021 if (save_persistent_data()) {
4022 SLOGE("Setfield error, cannot save persistent data");
4023 goto out;
4024 }
4025 }
4026
Rubin Xu85c01f92014-10-13 12:49:54 +01004027 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07004028
4029out:
4030 return rc;
4031}
Paul Lawrencef4faa572014-01-29 13:31:03 -08004032
4033/* Checks userdata. Attempt to mount the volume if default-
4034 * encrypted.
4035 * On success trigger next init phase and return 0.
4036 * Currently do not handle failure - see TODO below.
4037 */
4038int cryptfs_mount_default_encrypted(void)
4039{
4040 char decrypt_state[PROPERTY_VALUE_MAX];
4041 property_get("vold.decrypt", decrypt_state, "0");
4042 if (!strcmp(decrypt_state, "0")) {
4043 SLOGE("Not encrypted - should not call here");
4044 } else {
4045 int crypt_type = cryptfs_get_password_type();
4046 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
4047 SLOGE("Bad crypt type - error");
4048 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
4049 SLOGD("Password is not default - "
4050 "starting min framework to prompt");
4051 property_set("vold.decrypt", "trigger_restart_min_framework");
4052 return 0;
4053 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
4054 SLOGD("Password is default - restarting filesystem");
4055 cryptfs_restart_internal(0);
4056 return 0;
4057 } else {
4058 SLOGE("Encrypted, default crypt type but can't decrypt");
4059 }
4060 }
4061
Paul Lawrence6bfed202014-07-28 12:47:22 -07004062 /** Corrupt. Allow us to boot into framework, which will detect bad
4063 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08004064 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07004065 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08004066 return 0;
4067}
4068
4069/* Returns type of the password, default, pattern, pin or password.
4070 */
4071int cryptfs_get_password_type(void)
4072{
4073 struct crypt_mnt_ftr crypt_ftr;
4074
4075 if (get_crypt_ftr_and_key(&crypt_ftr)) {
4076 SLOGE("Error getting crypt footer and key\n");
4077 return -1;
4078 }
4079
Paul Lawrence6bfed202014-07-28 12:47:22 -07004080 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
4081 return -1;
4082 }
4083
Paul Lawrencef4faa572014-01-29 13:31:03 -08004084 return crypt_ftr.crypt_type;
4085}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08004086
Paul Lawrence399317e2014-03-10 13:20:50 -07004087char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08004088{
Paul Lawrence399317e2014-03-10 13:20:50 -07004089 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08004090 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07004091 if (now.tv_sec < password_expiry_time) {
4092 return password;
4093 } else {
4094 cryptfs_clear_password();
4095 return 0;
4096 }
4097}
4098
4099void cryptfs_clear_password()
4100{
4101 if (password) {
4102 size_t len = strlen(password);
4103 memset(password, 0, len);
4104 free(password);
4105 password = 0;
4106 password_expiry_time = 0;
4107 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08004108}