blob: 355d5912222d8bc337989f94bce47a02af9c656c [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
23#include <sys/types.h>
Ken Sumralle550f782013-08-20 13:48:23 -070024#include <sys/wait.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080025#include <sys/stat.h>
Paul Lawrencef4faa572014-01-29 13:31:03 -080026#include <ctype.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080027#include <fcntl.h>
Elliott Hughes73737162014-06-25 17:27:42 -070028#include <inttypes.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080029#include <unistd.h>
30#include <stdio.h>
31#include <sys/ioctl.h>
32#include <linux/dm-ioctl.h>
33#include <libgen.h>
34#include <stdlib.h>
35#include <sys/param.h>
36#include <string.h>
37#include <sys/mount.h>
38#include <openssl/evp.h>
Adam Langley41405bb2015-01-22 16:45:28 -080039#include <openssl/sha.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080040#include <errno.h>
Ken Sumrall3ed82362011-01-28 23:31:16 -080041#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070042#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070043#include <fs_mgr.h>
Paul Lawrence9c58a872014-09-30 09:12:51 -070044#include <time.h>
Rubin Xu85c01f92014-10-13 12:49:54 +010045#include <math.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080046#include "cryptfs.h"
47#define LOG_TAG "Cryptfs"
48#include "cutils/log.h"
49#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070050#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080051#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070052#include <logwrap/logwrap.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070053#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070054#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070055#include "crypto_scrypt.h"
Paul Lawrence731a7a22015-04-28 22:14:15 +000056#include "Ext4Crypt.h"
57#include "ext4_crypt_init_extensions.h"
Paul Lawrenceae59fe62014-01-21 08:23:27 -080058#include "ext4_utils.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000059#include "f2fs_sparseblock.h"
Paul Lawrence87999172014-02-20 12:21:31 -080060#include "CheckBattery.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080061#include "Process.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080062
Shawn Willden8af33352015-02-24 09:51:34 -070063#include <hardware/keymaster0.h>
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070064
Mark Salyzyn3e971272014-01-21 13:27:04 -080065#define UNUSED __attribute__((unused))
66
Mark Salyzyn5eecc442014-02-12 14:16:14 -080067#define UNUSED __attribute__((unused))
68
Ajay Dudani87701e22014-09-17 21:02:52 -070069#ifdef CONFIG_HW_DISK_ENCRYPTION
70#include "cryptfs_hw.h"
71#endif
72
Ken Sumrall8f869aa2010-12-03 03:47:09 -080073#define DM_CRYPT_BUF_SIZE 4096
74
Jason parks70a4b3f2011-01-28 10:10:47 -060075#define HASH_COUNT 2000
76#define KEY_LEN_BYTES 16
77#define IV_LEN_BYTES 16
78
Ken Sumrall29d8da82011-05-18 17:20:07 -070079#define KEY_IN_FOOTER "footer"
80
Paul Lawrence3bd36d52015-06-09 13:37:44 -070081#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080082
Ken Sumrall29d8da82011-05-18 17:20:07 -070083#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070084#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070085
Ken Sumralle919efe2012-09-29 17:07:41 -070086#define TABLE_LOAD_RETRIES 10
87
Shawn Willden47ba10d2014-09-03 17:07:06 -060088#define RSA_KEY_SIZE 2048
89#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
90#define RSA_EXPONENT 0x10001
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070091
Paul Lawrence8e3f4512014-09-08 10:11:17 -070092#define RETRY_MOUNT_ATTEMPTS 10
93#define RETRY_MOUNT_DELAY_SECONDS 1
94
Ken Sumrall8f869aa2010-12-03 03:47:09 -080095char *me = "cryptfs";
96
Jason parks70a4b3f2011-01-28 10:10:47 -060097static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070098static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060099static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700100static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800101
Shawn Willden8af33352015-02-24 09:51:34 -0700102static int keymaster_init(keymaster0_device_t **keymaster_dev)
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700103{
104 int rc;
105
106 const hw_module_t* mod;
107 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
108 if (rc) {
109 ALOGE("could not find any keystore module");
110 goto out;
111 }
112
Shawn Willden8af33352015-02-24 09:51:34 -0700113 rc = keymaster0_open(mod, keymaster_dev);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700114 if (rc) {
115 ALOGE("could not open keymaster device in %s (%s)",
116 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
117 goto out;
118 }
119
120 return 0;
121
122out:
123 *keymaster_dev = NULL;
124 return rc;
125}
126
127/* Should we use keymaster? */
128static int keymaster_check_compatibility()
129{
Shawn Willden8af33352015-02-24 09:51:34 -0700130 keymaster0_device_t *keymaster_dev = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700131 int rc = 0;
132
133 if (keymaster_init(&keymaster_dev)) {
134 SLOGE("Failed to init keymaster");
135 rc = -1;
136 goto out;
137 }
138
Paul Lawrence8c008392014-05-06 14:02:48 -0700139 SLOGI("keymaster version is %d", keymaster_dev->common.module->module_api_version);
140
141 if (keymaster_dev->common.module->module_api_version
142 < KEYMASTER_MODULE_API_VERSION_0_3) {
143 rc = 0;
144 goto out;
145 }
146
Shawn Willden7c49ab02014-10-30 08:12:32 -0600147 if (!(keymaster_dev->flags & KEYMASTER_SOFTWARE_ONLY) &&
148 (keymaster_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE)) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700149 rc = 1;
150 }
151
152out:
Shawn Willden8af33352015-02-24 09:51:34 -0700153 keymaster0_close(keymaster_dev);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700154 return rc;
155}
156
157/* Create a new keymaster key and store it in this footer */
158static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
159{
160 uint8_t* key = 0;
Shawn Willden8af33352015-02-24 09:51:34 -0700161 keymaster0_device_t *keymaster_dev = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700162
163 if (keymaster_init(&keymaster_dev)) {
164 SLOGE("Failed to init keymaster");
165 return -1;
166 }
167
168 int rc = 0;
169
170 keymaster_rsa_keygen_params_t params;
171 memset(&params, '\0', sizeof(params));
Shawn Willden47ba10d2014-09-03 17:07:06 -0600172 params.public_exponent = RSA_EXPONENT;
173 params.modulus_size = RSA_KEY_SIZE;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700174
175 size_t key_size;
176 if (keymaster_dev->generate_keypair(keymaster_dev, TYPE_RSA, &params,
177 &key, &key_size)) {
178 SLOGE("Failed to generate keypair");
179 rc = -1;
180 goto out;
181 }
182
183 if (key_size > KEYMASTER_BLOB_SIZE) {
184 SLOGE("Keymaster key too large for crypto footer");
185 rc = -1;
186 goto out;
187 }
188
189 memcpy(ftr->keymaster_blob, key, key_size);
190 ftr->keymaster_blob_size = key_size;
191
192out:
Shawn Willden8af33352015-02-24 09:51:34 -0700193 keymaster0_close(keymaster_dev);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700194 free(key);
195 return rc;
196}
197
Shawn Willdene17a9c42014-09-08 13:04:08 -0600198/* This signs the given object using the keymaster key. */
199static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600200 const unsigned char *object,
201 const size_t object_size,
202 unsigned char **signature,
203 size_t *signature_size)
204{
205 int rc = 0;
Shawn Willden8af33352015-02-24 09:51:34 -0700206 keymaster0_device_t *keymaster_dev = 0;
Shawn Willden47ba10d2014-09-03 17:07:06 -0600207 if (keymaster_init(&keymaster_dev)) {
208 SLOGE("Failed to init keymaster");
209 return -1;
210 }
211
212 /* We currently set the digest type to DIGEST_NONE because it's the
213 * only supported value for keymaster. A similar issue exists with
214 * PADDING_NONE. Long term both of these should likely change.
215 */
216 keymaster_rsa_sign_params_t params;
217 params.digest_type = DIGEST_NONE;
218 params.padding_type = PADDING_NONE;
219
220 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600221 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600222 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600223
Shawn Willdene17a9c42014-09-08 13:04:08 -0600224 // To sign a message with RSA, the message must satisfy two
225 // constraints:
226 //
227 // 1. The message, when interpreted as a big-endian numeric value, must
228 // be strictly less than the public modulus of the RSA key. Note
229 // that because the most significant bit of the public modulus is
230 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
231 // key), an n-bit message with most significant bit 0 always
232 // satisfies this requirement.
233 //
234 // 2. The message must have the same length in bits as the public
235 // modulus of the RSA key. This requirement isn't mathematically
236 // necessary, but is necessary to ensure consistency in
237 // implementations.
238 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600239 case KDF_SCRYPT_KEYMASTER:
240 // This ensures the most significant byte of the signed message
241 // is zero. We could have zero-padded to the left instead, but
242 // this approach is slightly more robust against changes in
243 // object size. However, it's still broken (but not unusably
244 // so) because we really should be using a proper RSA padding
245 // function, such as OAEP.
246 //
247 // TODO(paullawrence): When keymaster 0.4 is available, change
248 // this to use the padding options it provides.
249 memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
250 SLOGI("Signing safely-padded object");
251 break;
252 default:
253 SLOGE("Unknown KDF type %d", ftr->kdf_type);
254 return -1;
255 }
256
Shawn Willden47ba10d2014-09-03 17:07:06 -0600257 rc = keymaster_dev->sign_data(keymaster_dev,
258 &params,
259 ftr->keymaster_blob,
260 ftr->keymaster_blob_size,
261 to_sign,
Shawn Willdene17a9c42014-09-08 13:04:08 -0600262 to_sign_size,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600263 signature,
264 signature_size);
265
Shawn Willden8af33352015-02-24 09:51:34 -0700266 keymaster0_close(keymaster_dev);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600267 return rc;
268}
269
Paul Lawrence399317e2014-03-10 13:20:50 -0700270/* Store password when userdata is successfully decrypted and mounted.
271 * Cleared by cryptfs_clear_password
272 *
273 * To avoid a double prompt at boot, we need to store the CryptKeeper
274 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
275 * Since the entire framework is torn down and rebuilt after encryption,
276 * we have to use a daemon or similar to store the password. Since vold
277 * is secured against IPC except from system processes, it seems a reasonable
278 * place to store this.
279 *
280 * password should be cleared once it has been used.
281 *
282 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800283 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700284static char* password = 0;
285static int password_expiry_time = 0;
286static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800287
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800288extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800289
Paul Lawrence87999172014-02-20 12:21:31 -0800290enum RebootType {reboot, recovery, shutdown};
291static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700292{
Paul Lawrence87999172014-02-20 12:21:31 -0800293 switch(rt) {
294 case reboot:
295 property_set(ANDROID_RB_PROPERTY, "reboot");
296 break;
297
298 case recovery:
299 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
300 break;
301
302 case shutdown:
303 property_set(ANDROID_RB_PROPERTY, "shutdown");
304 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700305 }
Paul Lawrence87999172014-02-20 12:21:31 -0800306
Ken Sumralladfba362013-06-04 16:37:52 -0700307 sleep(20);
308
309 /* Shouldn't get here, reboot should happen before sleep times out */
310 return;
311}
312
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800313static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
314{
315 memset(io, 0, dataSize);
316 io->data_size = dataSize;
317 io->data_start = sizeof(struct dm_ioctl);
318 io->version[0] = 4;
319 io->version[1] = 0;
320 io->version[2] = 0;
321 io->flags = flags;
322 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100323 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800324 }
325}
326
Kenny Rootc4c70f12013-06-14 12:11:38 -0700327/**
328 * Gets the default device scrypt parameters for key derivation time tuning.
329 * The parameters should lead to about one second derivation time for the
330 * given device.
331 */
332static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
333 const int default_params[] = SCRYPT_DEFAULTS;
334 int params[] = SCRYPT_DEFAULTS;
335 char paramstr[PROPERTY_VALUE_MAX];
336 char *token;
337 char *saveptr;
338 int i;
339
340 property_get(SCRYPT_PROP, paramstr, "");
341 if (paramstr[0] != '\0') {
342 /*
343 * The token we're looking for should be three integers separated by
344 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
345 */
Kenny Root2947e342013-08-14 15:54:49 -0700346 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
347 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700348 i++, token = strtok_r(NULL, ":", &saveptr)) {
349 char *endptr;
350 params[i] = strtol(token, &endptr, 10);
351
352 /*
353 * Check that there was a valid number and it's 8-bit. If not,
354 * break out and the end check will take the default values.
355 */
356 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
357 break;
358 }
359 }
360
361 /*
362 * If there were not enough tokens or a token was malformed (not an
363 * integer), it will end up here and the default parameters can be
364 * taken.
365 */
366 if ((i != 3) || (token != NULL)) {
367 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
368 memcpy(params, default_params, sizeof(params));
369 }
370 }
371
372 ftr->N_factor = params[0];
373 ftr->r_factor = params[1];
374 ftr->p_factor = params[2];
375}
376
Ken Sumrall3ed82362011-01-28 23:31:16 -0800377static unsigned int get_fs_size(char *dev)
378{
379 int fd, block_size;
380 struct ext4_super_block sb;
381 off64_t len;
382
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700383 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800384 SLOGE("Cannot open device to get filesystem size ");
385 return 0;
386 }
387
388 if (lseek64(fd, 1024, SEEK_SET) < 0) {
389 SLOGE("Cannot seek to superblock");
390 return 0;
391 }
392
393 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
394 SLOGE("Cannot read superblock");
395 return 0;
396 }
397
398 close(fd);
399
Daniel Rosenberge82df162014-08-15 22:19:23 +0000400 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
401 SLOGE("Not a valid ext4 superblock");
402 return 0;
403 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800404 block_size = 1024 << sb.s_log_block_size;
405 /* compute length in bytes */
406 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
407
408 /* return length in sectors */
409 return (unsigned int) (len / 512);
410}
411
Ken Sumrall160b4d62013-04-22 12:15:39 -0700412static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
413{
414 static int cached_data = 0;
415 static off64_t cached_off = 0;
416 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
417 int fd;
418 char key_loc[PROPERTY_VALUE_MAX];
419 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700420 int rc = -1;
421
422 if (!cached_data) {
423 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
424
425 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700426 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700427 SLOGE("Cannot open real block device %s\n", real_blkdev);
428 return -1;
429 }
430
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900431 unsigned long nr_sec = 0;
432 get_blkdev_size(fd, &nr_sec);
433 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700434 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
435 * encryption info footer and key, and plenty of bytes to spare for future
436 * growth.
437 */
438 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
439 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
440 cached_data = 1;
441 } else {
442 SLOGE("Cannot get size of block device %s\n", real_blkdev);
443 }
444 close(fd);
445 } else {
446 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
447 cached_off = 0;
448 cached_data = 1;
449 }
450 }
451
452 if (cached_data) {
453 if (metadata_fname) {
454 *metadata_fname = cached_metadata_fname;
455 }
456 if (off) {
457 *off = cached_off;
458 }
459 rc = 0;
460 }
461
462 return rc;
463}
464
Ken Sumralle8744072011-01-18 22:01:55 -0800465/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800466 * update the failed mount count but not change the key.
467 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700468static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800469{
470 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800471 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700472 /* starting_off is set to the SEEK_SET offset
473 * where the crypto structure starts
474 */
475 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800476 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700477 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700478 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800479
Ken Sumrall160b4d62013-04-22 12:15:39 -0700480 if (get_crypt_ftr_info(&fname, &starting_off)) {
481 SLOGE("Unable to get crypt_ftr_info\n");
482 return -1;
483 }
484 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700485 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700486 return -1;
487 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700488 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700489 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700490 return -1;
491 }
492
493 /* Seek to the start of the crypt footer */
494 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
495 SLOGE("Cannot seek to real block device footer\n");
496 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800497 }
498
499 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
500 SLOGE("Cannot write real block device footer\n");
501 goto errout;
502 }
503
Ken Sumrall3be890f2011-09-14 16:53:46 -0700504 fstat(fd, &statbuf);
505 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700506 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700507 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800508 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800509 goto errout;
510 }
511 }
512
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800513 /* Success! */
514 rc = 0;
515
516errout:
517 close(fd);
518 return rc;
519
520}
521
Ken Sumrall160b4d62013-04-22 12:15:39 -0700522static inline int unix_read(int fd, void* buff, int len)
523{
524 return TEMP_FAILURE_RETRY(read(fd, buff, len));
525}
526
527static inline int unix_write(int fd, const void* buff, int len)
528{
529 return TEMP_FAILURE_RETRY(write(fd, buff, len));
530}
531
532static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
533{
534 memset(pdata, 0, len);
535 pdata->persist_magic = PERSIST_DATA_MAGIC;
536 pdata->persist_valid_entries = 0;
537}
538
539/* A routine to update the passed in crypt_ftr to the lastest version.
540 * fd is open read/write on the device that holds the crypto footer and persistent
541 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
542 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
543 */
544static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
545{
Kenny Root7434b312013-06-14 11:29:53 -0700546 int orig_major = crypt_ftr->major_version;
547 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700548
Kenny Root7434b312013-06-14 11:29:53 -0700549 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
550 struct crypt_persist_data *pdata;
551 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700552
Kenny Rootc4c70f12013-06-14 12:11:38 -0700553 SLOGW("upgrading crypto footer to 1.1");
554
Kenny Root7434b312013-06-14 11:29:53 -0700555 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
556 if (pdata == NULL) {
557 SLOGE("Cannot allocate persisent data\n");
558 return;
559 }
560 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
561
562 /* Need to initialize the persistent data area */
563 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
564 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100565 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700566 return;
567 }
568 /* Write all zeros to the first copy, making it invalid */
569 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
570
571 /* Write a valid but empty structure to the second copy */
572 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
573 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
574
575 /* Update the footer */
576 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
577 crypt_ftr->persist_data_offset[0] = pdata_offset;
578 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
579 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100580 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700581 }
582
Paul Lawrencef4faa572014-01-29 13:31:03 -0800583 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700584 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800585 /* But keep the old kdf_type.
586 * It will get updated later to KDF_SCRYPT after the password has been verified.
587 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700588 crypt_ftr->kdf_type = KDF_PBKDF2;
589 get_device_scrypt_params(crypt_ftr);
590 crypt_ftr->minor_version = 2;
591 }
592
Paul Lawrencef4faa572014-01-29 13:31:03 -0800593 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
594 SLOGW("upgrading crypto footer to 1.3");
595 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
596 crypt_ftr->minor_version = 3;
597 }
598
Kenny Root7434b312013-06-14 11:29:53 -0700599 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
600 if (lseek64(fd, offset, SEEK_SET) == -1) {
601 SLOGE("Cannot seek to crypt footer\n");
602 return;
603 }
604 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700605 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700606}
607
608
609static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800610{
611 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800612 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700613 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800614 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700615 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700616 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800617
Ken Sumrall160b4d62013-04-22 12:15:39 -0700618 if (get_crypt_ftr_info(&fname, &starting_off)) {
619 SLOGE("Unable to get crypt_ftr_info\n");
620 return -1;
621 }
622 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700623 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700624 return -1;
625 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700626 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700627 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700628 return -1;
629 }
630
631 /* Make sure it's 16 Kbytes in length */
632 fstat(fd, &statbuf);
633 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
634 SLOGE("footer file %s is not the expected size!\n", fname);
635 goto errout;
636 }
637
638 /* Seek to the start of the crypt footer */
639 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
640 SLOGE("Cannot seek to real block device footer\n");
641 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800642 }
643
644 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
645 SLOGE("Cannot read real block device footer\n");
646 goto errout;
647 }
648
649 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700650 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800651 goto errout;
652 }
653
Kenny Rootc96a5f82013-06-14 12:08:28 -0700654 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
655 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
656 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800657 goto errout;
658 }
659
Kenny Rootc96a5f82013-06-14 12:08:28 -0700660 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
661 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
662 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800663 }
664
Ken Sumrall160b4d62013-04-22 12:15:39 -0700665 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
666 * copy on disk before returning.
667 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700668 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700669 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800670 }
671
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800672 /* Success! */
673 rc = 0;
674
675errout:
676 close(fd);
677 return rc;
678}
679
Ken Sumrall160b4d62013-04-22 12:15:39 -0700680static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
681{
682 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
683 crypt_ftr->persist_data_offset[1]) {
684 SLOGE("Crypt_ftr persist data regions overlap");
685 return -1;
686 }
687
688 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
689 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
690 return -1;
691 }
692
693 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
694 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
695 CRYPT_FOOTER_OFFSET) {
696 SLOGE("Persistent data extends past crypto footer");
697 return -1;
698 }
699
700 return 0;
701}
702
703static int load_persistent_data(void)
704{
705 struct crypt_mnt_ftr crypt_ftr;
706 struct crypt_persist_data *pdata = NULL;
707 char encrypted_state[PROPERTY_VALUE_MAX];
708 char *fname;
709 int found = 0;
710 int fd;
711 int ret;
712 int i;
713
714 if (persist_data) {
715 /* Nothing to do, we've already loaded or initialized it */
716 return 0;
717 }
718
719
720 /* If not encrypted, just allocate an empty table and initialize it */
721 property_get("ro.crypto.state", encrypted_state, "");
722 if (strcmp(encrypted_state, "encrypted") ) {
723 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
724 if (pdata) {
725 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
726 persist_data = pdata;
727 return 0;
728 }
729 return -1;
730 }
731
732 if(get_crypt_ftr_and_key(&crypt_ftr)) {
733 return -1;
734 }
735
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700736 if ((crypt_ftr.major_version < 1)
737 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700738 SLOGE("Crypt_ftr version doesn't support persistent data");
739 return -1;
740 }
741
742 if (get_crypt_ftr_info(&fname, NULL)) {
743 return -1;
744 }
745
746 ret = validate_persistent_data_storage(&crypt_ftr);
747 if (ret) {
748 return -1;
749 }
750
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700751 fd = open(fname, O_RDONLY|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700752 if (fd < 0) {
753 SLOGE("Cannot open %s metadata file", fname);
754 return -1;
755 }
756
757 if (persist_data == NULL) {
758 pdata = malloc(crypt_ftr.persist_data_size);
759 if (pdata == NULL) {
760 SLOGE("Cannot allocate memory for persistent data");
761 goto err;
762 }
763 }
764
765 for (i = 0; i < 2; i++) {
766 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
767 SLOGE("Cannot seek to read persistent data on %s", fname);
768 goto err2;
769 }
770 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
771 SLOGE("Error reading persistent data on iteration %d", i);
772 goto err2;
773 }
774 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
775 found = 1;
776 break;
777 }
778 }
779
780 if (!found) {
781 SLOGI("Could not find valid persistent data, creating");
782 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
783 }
784
785 /* Success */
786 persist_data = pdata;
787 close(fd);
788 return 0;
789
790err2:
791 free(pdata);
792
793err:
794 close(fd);
795 return -1;
796}
797
798static int save_persistent_data(void)
799{
800 struct crypt_mnt_ftr crypt_ftr;
801 struct crypt_persist_data *pdata;
802 char *fname;
803 off64_t write_offset;
804 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700805 int fd;
806 int ret;
807
808 if (persist_data == NULL) {
809 SLOGE("No persistent data to save");
810 return -1;
811 }
812
813 if(get_crypt_ftr_and_key(&crypt_ftr)) {
814 return -1;
815 }
816
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700817 if ((crypt_ftr.major_version < 1)
818 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700819 SLOGE("Crypt_ftr version doesn't support persistent data");
820 return -1;
821 }
822
823 ret = validate_persistent_data_storage(&crypt_ftr);
824 if (ret) {
825 return -1;
826 }
827
828 if (get_crypt_ftr_info(&fname, NULL)) {
829 return -1;
830 }
831
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700832 fd = open(fname, O_RDWR|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700833 if (fd < 0) {
834 SLOGE("Cannot open %s metadata file", fname);
835 return -1;
836 }
837
838 pdata = malloc(crypt_ftr.persist_data_size);
839 if (pdata == NULL) {
840 SLOGE("Cannot allocate persistant data");
841 goto err;
842 }
843
844 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
845 SLOGE("Cannot seek to read persistent data on %s", fname);
846 goto err2;
847 }
848
849 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
850 SLOGE("Error reading persistent data before save");
851 goto err2;
852 }
853
854 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
855 /* The first copy is the curent valid copy, so write to
856 * the second copy and erase this one */
857 write_offset = crypt_ftr.persist_data_offset[1];
858 erase_offset = crypt_ftr.persist_data_offset[0];
859 } else {
860 /* The second copy must be the valid copy, so write to
861 * the first copy, and erase the second */
862 write_offset = crypt_ftr.persist_data_offset[0];
863 erase_offset = crypt_ftr.persist_data_offset[1];
864 }
865
866 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100867 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700868 SLOGE("Cannot seek to write persistent data");
869 goto err2;
870 }
871 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
872 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100873 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700874 SLOGE("Cannot seek to erase previous persistent data");
875 goto err2;
876 }
877 fsync(fd);
878 memset(pdata, 0, crypt_ftr.persist_data_size);
879 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
880 (int) crypt_ftr.persist_data_size) {
881 SLOGE("Cannot write to erase previous persistent data");
882 goto err2;
883 }
884 fsync(fd);
885 } else {
886 SLOGE("Cannot write to save persistent data");
887 goto err2;
888 }
889
890 /* Success */
891 free(pdata);
892 close(fd);
893 return 0;
894
895err2:
896 free(pdata);
897err:
898 close(fd);
899 return -1;
900}
901
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800902/* Convert a binary key of specified length into an ascii hex string equivalent,
903 * without the leading 0x and with null termination
904 */
Jeff Sharkey9c484982015-03-31 10:35:33 -0700905static void convert_key_to_hex_ascii(const unsigned char *master_key,
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700906 unsigned int keysize, char *master_key_ascii) {
907 unsigned int i, a;
908 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800909
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700910 for (i=0, a=0; i<keysize; i++, a+=2) {
911 /* For each byte, write out two ascii hex digits */
912 nibble = (master_key[i] >> 4) & 0xf;
913 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800914
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700915 nibble = master_key[i] & 0xf;
916 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
917 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800918
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700919 /* Add the null termination */
920 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800921
922}
923
Jeff Sharkey9c484982015-03-31 10:35:33 -0700924static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
925 const unsigned char *master_key, const char *real_blk_name,
926 const char *name, int fd, const char *extra_params) {
Dan Albertc07fa3f2014-12-18 10:00:55 -0800927 _Alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800928 struct dm_ioctl *io;
929 struct dm_target_spec *tgt;
930 char *crypt_params;
931 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
932 int i;
933
934 io = (struct dm_ioctl *) buffer;
935
936 /* Load the mapping table for this device */
937 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
938
939 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
940 io->target_count = 1;
941 tgt->status = 0;
942 tgt->sector_start = 0;
943 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -0700944#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -0800945 if (!strcmp((char *)crypt_ftr->crypto_type_name, "aes-xts")) {
946 strlcpy(tgt->target_type, "req-crypt", DM_MAX_TYPE_NAME);
947 }
948 else {
949 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
950 }
Ajay Dudani87701e22014-09-17 21:02:52 -0700951#else
952 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
953#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -0800954
955 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
956 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
957 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
958 master_key_ascii, real_blk_name, extra_params);
959 crypt_params += strlen(crypt_params) + 1;
960 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
961 tgt->next = crypt_params - buffer;
962
963 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
964 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
965 break;
966 }
967 usleep(500000);
968 }
969
970 if (i == TABLE_LOAD_RETRIES) {
971 /* We failed to load the table, return an error */
972 return -1;
973 } else {
974 return i + 1;
975 }
976}
977
978
979static int get_dm_crypt_version(int fd, const char *name, int *version)
980{
981 char buffer[DM_CRYPT_BUF_SIZE];
982 struct dm_ioctl *io;
983 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800984
985 io = (struct dm_ioctl *) buffer;
986
987 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
988
989 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
990 return -1;
991 }
992
993 /* Iterate over the returned versions, looking for name of "crypt".
994 * When found, get and return the version.
995 */
996 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
997 while (v->next) {
Ajay Dudani87701e22014-09-17 21:02:52 -0700998#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -0800999 if (! strcmp(v->name, "crypt") || ! strcmp(v->name, "req-crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001000#else
Ken Sumralldb5e0262013-02-05 17:39:48 -08001001 if (! strcmp(v->name, "crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001002#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001003 /* We found the crypt driver, return the version, and get out */
1004 version[0] = v->version[0];
1005 version[1] = v->version[1];
1006 version[2] = v->version[2];
1007 return 0;
1008 }
1009 v = (struct dm_target_versions *)(((char *)v) + v->next);
1010 }
1011
1012 return -1;
1013}
1014
Jeff Sharkey9c484982015-03-31 10:35:33 -07001015static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr,
1016 const unsigned char *master_key, const char *real_blk_name,
1017 char *crypto_blk_name, const char *name) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001018 char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001019 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001020 unsigned int minor;
Ajay Dudani87701e22014-09-17 21:02:52 -07001021 int fd=0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001022 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001023 int version[3];
1024 char *extra_params;
1025 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001026
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001027 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001028 SLOGE("Cannot open device-mapper\n");
1029 goto errout;
1030 }
1031
1032 io = (struct dm_ioctl *) buffer;
1033
1034 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1035 if (ioctl(fd, DM_DEV_CREATE, io)) {
1036 SLOGE("Cannot create dm-crypt device\n");
1037 goto errout;
1038 }
1039
1040 /* Get the device status, in particular, the name of it's device file */
1041 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1042 if (ioctl(fd, DM_DEV_STATUS, io)) {
1043 SLOGE("Cannot retrieve dm-crypt device status\n");
1044 goto errout;
1045 }
1046 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1047 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1048
Ken Sumralldb5e0262013-02-05 17:39:48 -08001049 extra_params = "";
1050 if (! get_dm_crypt_version(fd, name, version)) {
1051 /* Support for allow_discards was added in version 1.11.0 */
1052 if ((version[0] >= 2) ||
1053 ((version[0] == 1) && (version[1] >= 11))) {
1054 extra_params = "1 allow_discards";
1055 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1056 }
Ken Sumralle919efe2012-09-29 17:07:41 -07001057 }
1058
Ken Sumralldb5e0262013-02-05 17:39:48 -08001059 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1060 fd, extra_params);
1061 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001062 SLOGE("Cannot load dm-crypt mapping table.\n");
1063 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001064 } else if (load_count > 1) {
1065 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001066 }
1067
1068 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -08001069 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001070
1071 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1072 SLOGE("Cannot resume the dm-crypt device\n");
1073 goto errout;
1074 }
1075
1076 /* We made it here with no errors. Woot! */
1077 retval = 0;
1078
1079errout:
1080 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1081
1082 return retval;
1083}
1084
Ken Sumrall29d8da82011-05-18 17:20:07 -07001085static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001086{
1087 int fd;
1088 char buffer[DM_CRYPT_BUF_SIZE];
1089 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001090 int retval = -1;
1091
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001092 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001093 SLOGE("Cannot open device-mapper\n");
1094 goto errout;
1095 }
1096
1097 io = (struct dm_ioctl *) buffer;
1098
1099 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1100 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1101 SLOGE("Cannot remove dm-crypt device\n");
1102 goto errout;
1103 }
1104
1105 /* We made it here with no errors. Woot! */
1106 retval = 0;
1107
1108errout:
1109 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1110
1111 return retval;
1112
1113}
1114
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001115static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001116 unsigned char *ikey, void *params UNUSED)
1117{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001118 SLOGI("Using pbkdf2 for cryptfs KDF");
1119
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001120 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001121 PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd),
1122 salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001123 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001124
Paul Lawrencef4faa572014-01-29 13:31:03 -08001125 return 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001126}
1127
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001128static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001129 unsigned char *ikey, void *params)
1130{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001131 SLOGI("Using scrypt for cryptfs KDF");
1132
Kenny Rootc4c70f12013-06-14 12:11:38 -07001133 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1134
1135 int N = 1 << ftr->N_factor;
1136 int r = 1 << ftr->r_factor;
1137 int p = 1 << ftr->p_factor;
1138
1139 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001140 unsigned int keysize;
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001141 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1142 salt, SALT_LEN, N, r, p, ikey,
1143 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001144
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001145 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001146}
1147
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001148static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1149 unsigned char *ikey, void *params)
1150{
1151 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1152
1153 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001154 size_t signature_size;
1155 unsigned char* signature;
1156 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1157
1158 int N = 1 << ftr->N_factor;
1159 int r = 1 << ftr->r_factor;
1160 int p = 1 << ftr->p_factor;
1161
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001162 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1163 salt, SALT_LEN, N, r, p, ikey,
1164 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001165
1166 if (rc) {
1167 SLOGE("scrypt failed");
1168 return -1;
1169 }
1170
Shawn Willdene17a9c42014-09-08 13:04:08 -06001171 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1172 &signature, &signature_size)) {
1173 SLOGE("Signing failed");
1174 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001175 }
1176
1177 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1178 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1179 free(signature);
1180
1181 if (rc) {
1182 SLOGE("scrypt failed");
1183 return -1;
1184 }
1185
1186 return 0;
1187}
1188
1189static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1190 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001191 unsigned char *encrypted_master_key,
1192 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001193{
1194 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1195 EVP_CIPHER_CTX e_ctx;
1196 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001197 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001198
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001199 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001200 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001201
1202 switch (crypt_ftr->kdf_type) {
1203 case KDF_SCRYPT_KEYMASTER:
1204 if (keymaster_create_key(crypt_ftr)) {
1205 SLOGE("keymaster_create_key failed");
1206 return -1;
1207 }
1208
1209 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1210 SLOGE("scrypt failed");
1211 return -1;
1212 }
1213 break;
1214
1215 case KDF_SCRYPT:
1216 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1217 SLOGE("scrypt failed");
1218 return -1;
1219 }
1220 break;
1221
1222 default:
1223 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001224 return -1;
1225 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001226
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001227 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001228 EVP_CIPHER_CTX_init(&e_ctx);
1229 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001230 SLOGE("EVP_EncryptInit failed\n");
1231 return -1;
1232 }
1233 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001234
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001235 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001236 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Paul Lawrence731a7a22015-04-28 22:14:15 +00001237 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001238 SLOGE("EVP_EncryptUpdate failed\n");
1239 return -1;
1240 }
Adam Langley889c4f12014-09-03 14:23:13 -07001241 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001242 SLOGE("EVP_EncryptFinal failed\n");
1243 return -1;
1244 }
1245
1246 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1247 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1248 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001249 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001250
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001251 /* Store the scrypt of the intermediate key, so we can validate if it's a
1252 password error or mount error when things go wrong.
1253 Note there's no need to check for errors, since if this is incorrect, we
1254 simply won't wipe userdata, which is the correct default behavior
1255 */
1256 int N = 1 << crypt_ftr->N_factor;
1257 int r = 1 << crypt_ftr->r_factor;
1258 int p = 1 << crypt_ftr->p_factor;
1259
1260 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1261 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1262 crypt_ftr->scrypted_intermediate_key,
1263 sizeof(crypt_ftr->scrypted_intermediate_key));
1264
1265 if (rc) {
1266 SLOGE("encrypt_master_key: crypto_scrypt failed");
1267 }
1268
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001269 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001270}
1271
Paul Lawrence731a7a22015-04-28 22:14:15 +00001272static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001273 unsigned char *encrypted_master_key,
1274 unsigned char *decrypted_master_key,
1275 kdf_func kdf, void *kdf_params,
1276 unsigned char** intermediate_key,
1277 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001278{
1279 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 -08001280 EVP_CIPHER_CTX d_ctx;
1281 int decrypted_len, final_len;
1282
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001283 /* Turn the password into an intermediate key and IV that can decrypt the
1284 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001285 if (kdf(passwd, salt, ikey, kdf_params)) {
1286 SLOGE("kdf failed");
1287 return -1;
1288 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001289
1290 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001291 EVP_CIPHER_CTX_init(&d_ctx);
1292 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001293 return -1;
1294 }
1295 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1296 /* Decrypt the master key */
1297 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1298 encrypted_master_key, KEY_LEN_BYTES)) {
1299 return -1;
1300 }
Adam Langley889c4f12014-09-03 14:23:13 -07001301 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001302 return -1;
1303 }
1304
1305 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1306 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001307 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001308
1309 /* Copy intermediate key if needed by params */
1310 if (intermediate_key && intermediate_key_size) {
1311 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1312 if (intermediate_key) {
1313 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1314 *intermediate_key_size = KEY_LEN_BYTES;
1315 }
1316 }
1317
1318 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001319}
1320
Kenny Rootc4c70f12013-06-14 12:11:38 -07001321static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001322{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001323 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001324 *kdf = scrypt_keymaster;
1325 *kdf_params = ftr;
1326 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001327 *kdf = scrypt;
1328 *kdf_params = ftr;
1329 } else {
1330 *kdf = pbkdf2;
1331 *kdf_params = NULL;
1332 }
1333}
1334
Paul Lawrence731a7a22015-04-28 22:14:15 +00001335static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001336 struct crypt_mnt_ftr *crypt_ftr,
1337 unsigned char** intermediate_key,
1338 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001339{
1340 kdf_func kdf;
1341 void *kdf_params;
1342 int ret;
1343
1344 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001345 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1346 decrypted_master_key, kdf, kdf_params,
1347 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001348 if (ret != 0) {
1349 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001350 }
1351
1352 return ret;
1353}
1354
1355static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1356 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001357 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001358 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001359
1360 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001361 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001362 read(fd, key_buf, sizeof(key_buf));
1363 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001364 close(fd);
1365
1366 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001367 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001368}
1369
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001370int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001371{
Greg Hackmann955653e2014-09-24 14:55:20 -07001372 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001373#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001374
1375 /* Now umount the tmpfs filesystem */
1376 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001377 if (umount(mountpoint) == 0) {
1378 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001379 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001380
1381 if (errno == EINVAL) {
1382 /* EINVAL is returned if the directory is not a mountpoint,
1383 * i.e. there is no filesystem mounted there. So just get out.
1384 */
1385 break;
1386 }
1387
1388 err = errno;
1389
1390 /* If allowed, be increasingly aggressive before the last two retries */
1391 if (kill) {
1392 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1393 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001394 vold_killProcessesWithOpenFiles(mountpoint, SIGTERM);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001395 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1396 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001397 vold_killProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001398 }
1399 }
1400
1401 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001402 }
1403
1404 if (i < WAIT_UNMOUNT_COUNT) {
1405 SLOGD("unmounting %s succeeded\n", mountpoint);
1406 rc = 0;
1407 } else {
jessica_yu3f14fe42014-09-22 15:57:40 +08001408 vold_killProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001409 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001410 rc = -1;
1411 }
1412
1413 return rc;
1414}
1415
Ken Sumrallc5872692013-05-14 15:26:31 -07001416#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001417static int prep_data_fs(void)
1418{
1419 int i;
1420
1421 /* Do the prep of the /data filesystem */
1422 property_set("vold.post_fs_data_done", "0");
1423 property_set("vold.decrypt", "trigger_post_fs_data");
1424 SLOGD("Just triggered post_fs_data\n");
1425
Ken Sumrallc5872692013-05-14 15:26:31 -07001426 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001427 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001428 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001429
1430 property_get("vold.post_fs_data_done", p, "0");
1431 if (*p == '1') {
1432 break;
1433 } else {
1434 usleep(250000);
1435 }
1436 }
1437 if (i == DATA_PREP_TIMEOUT) {
1438 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001439 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001440 return -1;
1441 } else {
1442 SLOGD("post_fs_data done\n");
1443 return 0;
1444 }
1445}
1446
Paul Lawrence74f29f12014-08-28 15:54:10 -07001447static void cryptfs_set_corrupt()
1448{
1449 // Mark the footer as bad
1450 struct crypt_mnt_ftr crypt_ftr;
1451 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1452 SLOGE("Failed to get crypto footer - panic");
1453 return;
1454 }
1455
1456 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1457 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1458 SLOGE("Failed to set crypto footer - panic");
1459 return;
1460 }
1461}
1462
1463static void cryptfs_trigger_restart_min_framework()
1464{
1465 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1466 SLOGE("Failed to mount tmpfs on data - panic");
1467 return;
1468 }
1469
1470 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1471 SLOGE("Failed to trigger post fs data - panic");
1472 return;
1473 }
1474
1475 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1476 SLOGE("Failed to trigger restart min framework - panic");
1477 return;
1478 }
1479}
1480
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001481/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001482static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001483{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001484 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001485 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001486 static int restart_successful = 0;
1487
1488 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001489 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001490 SLOGE("Encrypted filesystem not validated, aborting");
1491 return -1;
1492 }
1493
1494 if (restart_successful) {
1495 SLOGE("System already restarted with encrypted disk, aborting");
1496 return -1;
1497 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001498
Paul Lawrencef4faa572014-01-29 13:31:03 -08001499 if (restart_main) {
1500 /* Here is where we shut down the framework. The init scripts
1501 * start all services in one of three classes: core, main or late_start.
1502 * On boot, we start core and main. Now, we stop main, but not core,
1503 * as core includes vold and a few other really important things that
1504 * we need to keep running. Once main has stopped, we should be able
1505 * to umount the tmpfs /data, then mount the encrypted /data.
1506 * We then restart the class main, and also the class late_start.
1507 * At the moment, I've only put a few things in late_start that I know
1508 * are not needed to bring up the framework, and that also cause problems
1509 * with unmounting the tmpfs /data, but I hope to add add more services
1510 * to the late_start class as we optimize this to decrease the delay
1511 * till the user is asked for the password to the filesystem.
1512 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001513
Paul Lawrencef4faa572014-01-29 13:31:03 -08001514 /* The init files are setup to stop the class main when vold.decrypt is
1515 * set to trigger_reset_main.
1516 */
1517 property_set("vold.decrypt", "trigger_reset_main");
1518 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001519
Paul Lawrencef4faa572014-01-29 13:31:03 -08001520 /* Ugh, shutting down the framework is not synchronous, so until it
1521 * can be fixed, this horrible hack will wait a moment for it all to
1522 * shut down before proceeding. Without it, some devices cannot
1523 * restart the graphics services.
1524 */
1525 sleep(2);
1526 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001527
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001528 /* Now that the framework is shutdown, we should be able to umount()
1529 * the tmpfs filesystem, and mount the real one.
1530 */
1531
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001532 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1533 if (strlen(crypto_blkdev) == 0) {
1534 SLOGE("fs_crypto_blkdev not set\n");
1535 return -1;
1536 }
1537
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001538 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001539 /* If ro.crypto.readonly is set to 1, mount the decrypted
1540 * filesystem readonly. This is used when /data is mounted by
1541 * recovery mode.
1542 */
1543 char ro_prop[PROPERTY_VALUE_MAX];
1544 property_get("ro.crypto.readonly", ro_prop, "");
1545 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1546 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1547 rec->flags |= MS_RDONLY;
1548 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001549
Ken Sumralle5032c42012-04-01 23:58:44 -07001550 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001551 int retries = RETRY_MOUNT_ATTEMPTS;
1552 int mount_rc;
1553 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1554 crypto_blkdev, 0))
1555 != 0) {
1556 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1557 /* TODO: invoke something similar to
1558 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1559 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1560 SLOGI("Failed to mount %s because it is busy - waiting",
1561 crypto_blkdev);
1562 if (--retries) {
1563 sleep(RETRY_MOUNT_DELAY_SECONDS);
1564 } else {
1565 /* Let's hope that a reboot clears away whatever is keeping
1566 the mount busy */
1567 cryptfs_reboot(reboot);
1568 }
1569 } else {
1570 SLOGE("Failed to mount decrypted data");
1571 cryptfs_set_corrupt();
1572 cryptfs_trigger_restart_min_framework();
1573 SLOGI("Started framework to offer wipe");
1574 return -1;
1575 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001576 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001577
Ken Sumralle5032c42012-04-01 23:58:44 -07001578 property_set("vold.decrypt", "trigger_load_persist_props");
1579 /* Create necessary paths on /data */
1580 if (prep_data_fs()) {
1581 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001582 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001583
1584 /* startup service classes main and late_start */
1585 property_set("vold.decrypt", "trigger_restart_framework");
1586 SLOGD("Just triggered restart_framework\n");
1587
1588 /* Give it a few moments to get started */
1589 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001590 }
1591
Ken Sumrall0cc16632011-01-18 20:32:26 -08001592 if (rc == 0) {
1593 restart_successful = 1;
1594 }
1595
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001596 return rc;
1597}
1598
Paul Lawrencef4faa572014-01-29 13:31:03 -08001599int cryptfs_restart(void)
1600{
Paul Lawrence05335c32015-03-05 09:46:23 -08001601 SLOGI("cryptfs_restart");
1602 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
1603 struct fstab_rec* rec;
1604 int rc;
1605
1606 if (e4crypt_restart(DATA_MNT_POINT)) {
1607 SLOGE("Can't unmount e4crypt temp volume\n");
1608 return -1;
1609 }
1610
1611 rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1612 if (!rec) {
1613 SLOGE("Can't get fstab record for %s\n", DATA_MNT_POINT);
1614 return -1;
1615 }
1616
1617 rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT, rec->blk_device, 0);
1618 if (rc) {
1619 SLOGE("Can't mount %s\n", DATA_MNT_POINT);
1620 return rc;
1621 }
1622
1623 property_set("vold.decrypt", "trigger_restart_framework");
1624 return 0;
1625 }
1626
Paul Lawrencef4faa572014-01-29 13:31:03 -08001627 /* Call internal implementation forcing a restart of main service group */
1628 return cryptfs_restart_internal(1);
1629}
1630
Paul Lawrence05335c32015-03-05 09:46:23 -08001631static int do_crypto_complete(char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001632{
1633 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001634 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001635 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001636
1637 property_get("ro.crypto.state", encrypted_state, "");
1638 if (strcmp(encrypted_state, "encrypted") ) {
1639 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001640 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001641 }
1642
Paul Lawrence05335c32015-03-05 09:46:23 -08001643 if (e4crypt_crypto_complete(mount_point) == 0) {
1644 return CRYPTO_COMPLETE_ENCRYPTED;
1645 }
1646
Ken Sumrall160b4d62013-04-22 12:15:39 -07001647 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001648 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001649
Ken Sumralle1a45852011-12-14 21:24:27 -08001650 /*
1651 * Only report this error if key_loc is a file and it exists.
1652 * If the device was never encrypted, and /data is not mountable for
1653 * some reason, returning 1 should prevent the UI from presenting the
1654 * a "enter password" screen, or worse, a "press button to wipe the
1655 * device" screen.
1656 */
1657 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1658 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001659 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001660 } else {
1661 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001662 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001663 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001664 }
1665
Paul Lawrence74f29f12014-08-28 15:54:10 -07001666 // Test for possible error flags
1667 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1668 SLOGE("Encryption process is partway completed\n");
1669 return CRYPTO_COMPLETE_PARTIAL;
1670 }
1671
1672 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1673 SLOGE("Encryption process was interrupted but cannot continue\n");
1674 return CRYPTO_COMPLETE_INCONSISTENT;
1675 }
1676
1677 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1678 SLOGE("Encryption is successful but data is corrupt\n");
1679 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001680 }
1681
1682 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001683 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001684}
1685
Paul Lawrencef4faa572014-01-29 13:31:03 -08001686static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1687 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001688{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001689 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001690 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001691 char crypto_blkdev[MAXPATHLEN];
1692 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001693 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001694 unsigned int orig_failed_decrypt_count;
1695 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001696 int use_keymaster = 0;
1697 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001698 unsigned char* intermediate_key = 0;
1699 size_t intermediate_key_size = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001700
Paul Lawrencef4faa572014-01-29 13:31:03 -08001701 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1702 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001703
Paul Lawrencef4faa572014-01-29 13:31:03 -08001704 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001705 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1706 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001707 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001708 rc = -1;
1709 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001710 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001711 }
1712
Paul Lawrencef4faa572014-01-29 13:31:03 -08001713 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1714
Ajay Dudani87701e22014-09-17 21:02:52 -07001715#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001716 if (!strcmp((char *)crypt_ftr->crypto_type_name, "aes-xts")) {
1717 if(!set_hw_device_encryption_key(passwd, (char*) crypt_ftr->crypto_type_name)) {
1718 SLOGE("Hardware encryption key does not match");
1719 }
Ajay Dudani87701e22014-09-17 21:02:52 -07001720 }
1721#endif
1722
Paul Lawrence74f29f12014-08-28 15:54:10 -07001723 // Create crypto block device - all (non fatal) code paths
1724 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001725 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1726 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001727 SLOGE("Error creating decrypted block device\n");
1728 rc = -1;
1729 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001730 }
1731
Paul Lawrence74f29f12014-08-28 15:54:10 -07001732 /* Work out if the problem is the password or the data */
1733 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1734 scrypted_intermediate_key)];
1735 int N = 1 << crypt_ftr->N_factor;
1736 int r = 1 << crypt_ftr->r_factor;
1737 int p = 1 << crypt_ftr->p_factor;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001738
Paul Lawrence74f29f12014-08-28 15:54:10 -07001739 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1740 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1741 N, r, p, scrypted_intermediate_key,
1742 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001743
Paul Lawrence74f29f12014-08-28 15:54:10 -07001744 // Does the key match the crypto footer?
1745 if (rc == 0 && memcmp(scrypted_intermediate_key,
1746 crypt_ftr->scrypted_intermediate_key,
1747 sizeof(scrypted_intermediate_key)) == 0) {
1748 SLOGI("Password matches");
1749 rc = 0;
1750 } else {
1751 /* Try mounting the file system anyway, just in case the problem's with
1752 * the footer, not the key. */
1753 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1754 mkdir(tmp_mount_point, 0755);
1755 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1756 SLOGE("Error temp mounting decrypted block device\n");
1757 delete_crypto_blk_dev(label);
1758
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001759 rc = ++crypt_ftr->failed_decrypt_count;
1760 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001761 } else {
1762 /* Success! */
1763 SLOGI("Password did not match but decrypted drive mounted - continue");
1764 umount(tmp_mount_point);
1765 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001766 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001767 }
1768
1769 if (rc == 0) {
1770 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001771 if (orig_failed_decrypt_count != 0) {
1772 put_crypt_ftr_and_key(crypt_ftr);
1773 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001774
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001775 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001776 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001777 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001778
1779 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001780 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001781 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001782 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001783 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001784 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001785 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001786
Paul Lawrence74f29f12014-08-28 15:54:10 -07001787 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001788 use_keymaster = keymaster_check_compatibility();
1789 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001790 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001791 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1792 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1793 upgrade = 1;
1794 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001795 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001796 upgrade = 1;
1797 }
1798
1799 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001800 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1801 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001802 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001803 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001804 }
1805 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001806
1807 // Do not fail even if upgrade failed - machine is bootable
1808 // Note that if this code is ever hit, there is a *serious* problem
1809 // since KDFs should never fail. You *must* fix the kdf before
1810 // proceeding!
1811 if (rc) {
1812 SLOGW("Upgrade failed with error %d,"
1813 " but continuing with previous state",
1814 rc);
1815 rc = 0;
1816 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001817 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001818 }
1819
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001820 errout:
1821 if (intermediate_key) {
1822 memset(intermediate_key, 0, intermediate_key_size);
1823 free(intermediate_key);
1824 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001825 return rc;
1826}
1827
Ken Sumrall29d8da82011-05-18 17:20:07 -07001828/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07001829 * Called by vold when it's asked to mount an encrypted external
1830 * storage volume. The incoming partition has no crypto header/footer,
1831 * as any metadata is been stored in a separate, small partition.
1832 *
1833 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07001834 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001835int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1836 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001837 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001838 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001839 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001840 return -1;
1841 }
1842
1843 unsigned long nr_sec = 0;
1844 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001845 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001846
Ken Sumrall29d8da82011-05-18 17:20:07 -07001847 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001848 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001849 return -1;
1850 }
1851
Jeff Sharkey9c484982015-03-31 10:35:33 -07001852 struct crypt_mnt_ftr ext_crypt_ftr;
1853 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1854 ext_crypt_ftr.fs_size = nr_sec;
1855 ext_crypt_ftr.keysize = keysize;
1856 strcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001857
Jeff Sharkey9c484982015-03-31 10:35:33 -07001858 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev,
1859 out_crypto_blkdev, label);
1860}
Ken Sumrall29d8da82011-05-18 17:20:07 -07001861
Jeff Sharkey9c484982015-03-31 10:35:33 -07001862/*
1863 * Called by vold when it's asked to unmount an encrypted external
1864 * storage volume.
1865 */
1866int cryptfs_revert_ext_volume(const char* label) {
1867 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001868}
1869
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001870int cryptfs_crypto_complete(void)
1871{
1872 return do_crypto_complete("/data");
1873}
1874
Paul Lawrencef4faa572014-01-29 13:31:03 -08001875int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1876{
1877 char encrypted_state[PROPERTY_VALUE_MAX];
1878 property_get("ro.crypto.state", encrypted_state, "");
1879 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1880 SLOGE("encrypted fs already validated or not running with encryption,"
1881 " aborting");
1882 return -1;
1883 }
1884
1885 if (get_crypt_ftr_and_key(crypt_ftr)) {
1886 SLOGE("Error getting crypt footer and key");
1887 return -1;
1888 }
1889
1890 return 0;
1891}
1892
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001893int cryptfs_check_passwd(char *passwd)
1894{
Paul Lawrence05335c32015-03-05 09:46:23 -08001895 SLOGI("cryptfs_check_passwd");
1896 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
1897 return e4crypt_check_passwd(DATA_MNT_POINT, passwd);
1898 }
1899
Paul Lawrencef4faa572014-01-29 13:31:03 -08001900 struct crypt_mnt_ftr crypt_ftr;
1901 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001902
Paul Lawrencef4faa572014-01-29 13:31:03 -08001903 rc = check_unmounted_and_get_ftr(&crypt_ftr);
1904 if (rc)
1905 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001906
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001907 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
1908 DATA_MNT_POINT, "userdata");
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001909
1910 if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001911 cryptfs_clear_password();
1912 password = strdup(passwd);
1913 struct timespec now;
1914 clock_gettime(CLOCK_BOOTTIME, &now);
1915 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001916 }
1917
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001918 return rc;
1919}
1920
Ken Sumrall3ad90722011-10-04 20:38:29 -07001921int cryptfs_verify_passwd(char *passwd)
1922{
1923 struct crypt_mnt_ftr crypt_ftr;
1924 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001925 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001926 char encrypted_state[PROPERTY_VALUE_MAX];
1927 int rc;
1928
1929 property_get("ro.crypto.state", encrypted_state, "");
1930 if (strcmp(encrypted_state, "encrypted") ) {
1931 SLOGE("device not encrypted, aborting");
1932 return -2;
1933 }
1934
1935 if (!master_key_saved) {
1936 SLOGE("encrypted fs not yet mounted, aborting");
1937 return -1;
1938 }
1939
1940 if (!saved_mount_point) {
1941 SLOGE("encrypted fs failed to save mount point, aborting");
1942 return -1;
1943 }
1944
Ken Sumrall160b4d62013-04-22 12:15:39 -07001945 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001946 SLOGE("Error getting crypt footer and key\n");
1947 return -1;
1948 }
1949
1950 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1951 /* If the device has no password, then just say the password is valid */
1952 rc = 0;
1953 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001954 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001955 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1956 /* They match, the password is correct */
1957 rc = 0;
1958 } else {
1959 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1960 sleep(1);
1961 rc = 1;
1962 }
1963 }
1964
1965 return rc;
1966}
1967
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001968/* Initialize a crypt_mnt_ftr structure. The keysize is
1969 * defaulted to 16 bytes, and the filesystem size to 0.
1970 * Presumably, at a minimum, the caller will update the
1971 * filesystem size and crypto_type_name after calling this function.
1972 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001973static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001974{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001975 off64_t off;
1976
1977 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001978 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001979 ftr->major_version = CURRENT_MAJOR_VERSION;
1980 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001981 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001982 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001983
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001984 switch (keymaster_check_compatibility()) {
1985 case 1:
1986 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1987 break;
1988
1989 case 0:
1990 ftr->kdf_type = KDF_SCRYPT;
1991 break;
1992
1993 default:
1994 SLOGE("keymaster_check_compatibility failed");
1995 return -1;
1996 }
1997
Kenny Rootc4c70f12013-06-14 12:11:38 -07001998 get_device_scrypt_params(ftr);
1999
Ken Sumrall160b4d62013-04-22 12:15:39 -07002000 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2001 if (get_crypt_ftr_info(NULL, &off) == 0) {
2002 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
2003 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
2004 ftr->persist_data_size;
2005 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002006
2007 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002008}
2009
Ken Sumrall29d8da82011-05-18 17:20:07 -07002010static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002011{
Ken Sumralle550f782013-08-20 13:48:23 -07002012 const char *args[10];
2013 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
2014 int num_args;
2015 int status;
2016 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002017 int rc = -1;
2018
Ken Sumrall29d8da82011-05-18 17:20:07 -07002019 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07002020 args[0] = "/system/bin/make_ext4fs";
2021 args[1] = "-a";
2022 args[2] = "/data";
2023 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07002024 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07002025 args[4] = size_str;
2026 args[5] = crypto_blkdev;
2027 num_args = 6;
2028 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
2029 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07002030 } else if (type == F2FS_FS) {
2031 args[0] = "/system/bin/mkfs.f2fs";
2032 args[1] = "-t";
2033 args[2] = "-d1";
2034 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07002035 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07002036 args[4] = size_str;
2037 num_args = 5;
2038 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
2039 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002040 } else {
2041 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
2042 return -1;
2043 }
2044
Ken Sumralle550f782013-08-20 13:48:23 -07002045 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
2046
2047 if (tmp != 0) {
2048 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002049 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07002050 if (WIFEXITED(status)) {
2051 if (WEXITSTATUS(status)) {
2052 SLOGE("Error creating filesystem on %s, exit status %d ",
2053 crypto_blkdev, WEXITSTATUS(status));
2054 } else {
2055 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
2056 rc = 0;
2057 }
2058 } else {
2059 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
2060 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002061 }
2062
2063 return rc;
2064}
2065
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002066#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08002067#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
2068#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002069
2070/* aligned 32K writes tends to make flash happy.
2071 * SD card association recommends it.
2072 */
Ajay Dudani87701e22014-09-17 21:02:52 -07002073#ifndef CONFIG_HW_DISK_ENCRYPTION
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002074#define BLOCKS_AT_A_TIME 8
Ajay Dudani87701e22014-09-17 21:02:52 -07002075#else
2076#define BLOCKS_AT_A_TIME 1024
2077#endif
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002078
2079struct encryptGroupsData
2080{
2081 int realfd;
2082 int cryptofd;
2083 off64_t numblocks;
2084 off64_t one_pct, cur_pct, new_pct;
2085 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002086 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002087 char* real_blkdev, * crypto_blkdev;
2088 int count;
2089 off64_t offset;
2090 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08002091 off64_t last_written_sector;
2092 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002093 time_t time_started;
2094 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002095};
2096
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002097static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002098{
2099 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002100
2101 if (is_used) {
2102 data->used_blocks_already_done++;
2103 }
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002104 if (data->tot_used_blocks) {
2105 data->new_pct = data->used_blocks_already_done / data->one_pct;
2106 } else {
2107 data->new_pct = data->blocks_already_done / data->one_pct;
2108 }
2109
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002110 if (data->new_pct > data->cur_pct) {
2111 char buf[8];
2112 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07002113 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002114 property_set("vold.encrypt_progress", buf);
2115 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002116
2117 if (data->cur_pct >= 5) {
Paul Lawrence9c58a872014-09-30 09:12:51 -07002118 struct timespec time_now;
2119 if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
2120 SLOGW("Error getting time");
2121 } else {
2122 double elapsed_time = difftime(time_now.tv_sec, data->time_started);
2123 off64_t remaining_blocks = data->tot_used_blocks
2124 - data->used_blocks_already_done;
2125 int remaining_time = (int)(elapsed_time * remaining_blocks
2126 / data->used_blocks_already_done);
Paul Lawrence71577502014-08-13 14:55:55 -07002127
Paul Lawrence9c58a872014-09-30 09:12:51 -07002128 // Change time only if not yet set, lower, or a lot higher for
2129 // best user experience
2130 if (data->remaining_time == -1
2131 || remaining_time < data->remaining_time
2132 || remaining_time > data->remaining_time + 60) {
2133 char buf[8];
2134 snprintf(buf, sizeof(buf), "%d", remaining_time);
2135 property_set("vold.encrypt_time_remaining", buf);
2136 data->remaining_time = remaining_time;
2137 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002138 }
2139 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002140}
2141
Paul Lawrence3846be12014-09-22 11:33:54 -07002142static void log_progress(struct encryptGroupsData const* data, bool completed)
2143{
2144 // Precondition - if completed data = 0 else data != 0
2145
2146 // Track progress so we can skip logging blocks
2147 static off64_t offset = -1;
2148
2149 // Need to close existing 'Encrypting from' log?
2150 if (completed || (offset != -1 && data->offset != offset)) {
2151 SLOGI("Encrypted to sector %" PRId64,
2152 offset / info.block_size * CRYPT_SECTOR_SIZE);
2153 offset = -1;
2154 }
2155
2156 // Need to start new 'Encrypting from' log?
2157 if (!completed && offset != data->offset) {
2158 SLOGI("Encrypting from sector %" PRId64,
2159 data->offset / info.block_size * CRYPT_SECTOR_SIZE);
2160 }
2161
2162 // Update offset
2163 if (!completed) {
2164 offset = data->offset + (off64_t)data->count * info.block_size;
2165 }
2166}
2167
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002168static int flush_outstanding_data(struct encryptGroupsData* data)
2169{
2170 if (data->count == 0) {
2171 return 0;
2172 }
2173
Elliott Hughes231bdba2014-06-25 18:36:19 -07002174 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002175
2176 if (pread64(data->realfd, data->buffer,
2177 info.block_size * data->count, data->offset)
2178 <= 0) {
2179 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2180 data->real_blkdev);
2181 return -1;
2182 }
2183
2184 if (pwrite64(data->cryptofd, data->buffer,
2185 info.block_size * data->count, data->offset)
2186 <= 0) {
2187 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2188 data->crypto_blkdev);
2189 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002190 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002191 log_progress(data, false);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002192 }
2193
2194 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002195 data->last_written_sector = (data->offset + data->count)
2196 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002197 return 0;
2198}
2199
2200static int encrypt_groups(struct encryptGroupsData* data)
2201{
2202 unsigned int i;
2203 u8 *block_bitmap = 0;
2204 unsigned int block;
2205 off64_t ret;
2206 int rc = -1;
2207
2208 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
2209 if (!data->buffer) {
2210 SLOGE("Failed to allocate crypto buffer");
2211 goto errout;
2212 }
2213
2214 block_bitmap = malloc(info.block_size);
2215 if (!block_bitmap) {
2216 SLOGE("failed to allocate block bitmap");
2217 goto errout;
2218 }
2219
2220 for (i = 0; i < aux_info.groups; ++i) {
2221 SLOGI("Encrypting group %d", i);
2222
2223 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2224 u32 block_count = min(info.blocks_per_group,
2225 aux_info.len_blocks - first_block);
2226
2227 off64_t offset = (u64)info.block_size
2228 * aux_info.bg_desc[i].bg_block_bitmap;
2229
2230 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2231 if (ret != (int)info.block_size) {
2232 SLOGE("failed to read all of block group bitmap %d", i);
2233 goto errout;
2234 }
2235
2236 offset = (u64)info.block_size * first_block;
2237
2238 data->count = 0;
2239
2240 for (block = 0; block < block_count; block++) {
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002241 int used = bitmap_get_bit(block_bitmap, block);
2242 update_progress(data, used);
2243 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002244 if (data->count == 0) {
2245 data->offset = offset;
2246 }
2247 data->count++;
2248 } else {
2249 if (flush_outstanding_data(data)) {
2250 goto errout;
2251 }
2252 }
2253
2254 offset += info.block_size;
2255
2256 /* Write data if we are aligned or buffer size reached */
2257 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2258 || data->count == BLOCKS_AT_A_TIME) {
2259 if (flush_outstanding_data(data)) {
2260 goto errout;
2261 }
2262 }
Paul Lawrence87999172014-02-20 12:21:31 -08002263
Paul Lawrence73d7a022014-06-09 14:10:09 -07002264 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002265 SLOGE("Stopping encryption due to low battery");
2266 rc = 0;
2267 goto errout;
2268 }
2269
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002270 }
2271 if (flush_outstanding_data(data)) {
2272 goto errout;
2273 }
2274 }
2275
Paul Lawrence87999172014-02-20 12:21:31 -08002276 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002277 rc = 0;
2278
2279errout:
Paul Lawrence3846be12014-09-22 11:33:54 -07002280 log_progress(0, true);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002281 free(data->buffer);
2282 free(block_bitmap);
2283 return rc;
2284}
2285
2286static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2287 char *real_blkdev,
2288 off64_t size,
2289 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002290 off64_t tot_size,
2291 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002292{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002293 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002294 struct encryptGroupsData data;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002295 int rc; // Can't initialize without causing warning -Wclobbered
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002296
Paul Lawrence87999172014-02-20 12:21:31 -08002297 if (previously_encrypted_upto > *size_already_done) {
2298 SLOGD("Not fast encrypting since resuming part way through");
2299 return -1;
2300 }
2301
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002302 memset(&data, 0, sizeof(data));
2303 data.real_blkdev = real_blkdev;
2304 data.crypto_blkdev = crypto_blkdev;
2305
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002306 if ( (data.realfd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002307 SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
2308 real_blkdev, errno, strerror(errno));
Paul Lawrence74f29f12014-08-28 15:54:10 -07002309 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002310 goto errout;
2311 }
2312
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002313 if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002314 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
JP Abgrall3334c6a2014-10-10 15:52:11 -07002315 crypto_blkdev, errno, strerror(errno));
JP Abgrall7fc1de82014-10-10 18:43:41 -07002316 rc = ENABLE_INPLACE_ERR_DEV;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002317 goto errout;
2318 }
2319
2320 if (setjmp(setjmp_env)) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002321 SLOGE("Reading ext4 extent caused an exception\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002322 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002323 goto errout;
2324 }
2325
2326 if (read_ext(data.realfd, 0) != 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002327 SLOGE("Failed to read ext4 extent\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002328 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002329 goto errout;
2330 }
2331
2332 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2333 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2334 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2335
JP Abgrall7fc1de82014-10-10 18:43:41 -07002336 SLOGI("Encrypting ext4 filesystem in place...");
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002337
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002338 data.tot_used_blocks = data.numblocks;
2339 for (i = 0; i < aux_info.groups; ++i) {
2340 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2341 }
2342
2343 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002344 data.cur_pct = 0;
Paul Lawrence9c58a872014-09-30 09:12:51 -07002345
2346 struct timespec time_started = {0};
2347 if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
2348 SLOGW("Error getting time at start");
2349 // Note - continue anyway - we'll run with 0
2350 }
2351 data.time_started = time_started.tv_sec;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002352 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002353
2354 rc = encrypt_groups(&data);
2355 if (rc) {
2356 SLOGE("Error encrypting groups");
2357 goto errout;
2358 }
2359
Paul Lawrence87999172014-02-20 12:21:31 -08002360 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002361 rc = 0;
2362
2363errout:
2364 close(data.realfd);
2365 close(data.cryptofd);
2366
2367 return rc;
2368}
2369
Paul Lawrence3846be12014-09-22 11:33:54 -07002370static void log_progress_f2fs(u64 block, bool completed)
2371{
2372 // Precondition - if completed data = 0 else data != 0
2373
2374 // Track progress so we can skip logging blocks
2375 static u64 last_block = (u64)-1;
2376
2377 // Need to close existing 'Encrypting from' log?
2378 if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
2379 SLOGI("Encrypted to block %" PRId64, last_block);
2380 last_block = -1;
2381 }
2382
2383 // Need to start new 'Encrypting from' log?
2384 if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
2385 SLOGI("Encrypting from block %" PRId64, block);
2386 }
2387
2388 // Update offset
2389 if (!completed) {
2390 last_block = block;
2391 }
2392}
2393
Daniel Rosenberge82df162014-08-15 22:19:23 +00002394static int encrypt_one_block_f2fs(u64 pos, void *data)
2395{
2396 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2397
2398 priv_dat->blocks_already_done = pos - 1;
2399 update_progress(priv_dat, 1);
2400
2401 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2402
2403 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002404 SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002405 return -1;
2406 }
2407
2408 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002409 SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002410 return -1;
2411 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002412 log_progress_f2fs(pos, false);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002413 }
2414
2415 return 0;
2416}
2417
2418static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2419 char *real_blkdev,
2420 off64_t size,
2421 off64_t *size_already_done,
2422 off64_t tot_size,
2423 off64_t previously_encrypted_upto)
2424{
Daniel Rosenberge82df162014-08-15 22:19:23 +00002425 struct encryptGroupsData data;
2426 struct f2fs_info *f2fs_info = NULL;
JP Abgrall7fc1de82014-10-10 18:43:41 -07002427 int rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002428 if (previously_encrypted_upto > *size_already_done) {
2429 SLOGD("Not fast encrypting since resuming part way through");
JP Abgrall7fc1de82014-10-10 18:43:41 -07002430 return ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002431 }
2432 memset(&data, 0, sizeof(data));
2433 data.real_blkdev = real_blkdev;
2434 data.crypto_blkdev = crypto_blkdev;
2435 data.realfd = -1;
2436 data.cryptofd = -1;
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002437 if ( (data.realfd = open64(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002438 SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
Daniel Rosenberge82df162014-08-15 22:19:23 +00002439 real_blkdev);
2440 goto errout;
2441 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002442 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002443 SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
JP Abgrall3334c6a2014-10-10 15:52:11 -07002444 crypto_blkdev, errno, strerror(errno));
JP Abgrall7fc1de82014-10-10 18:43:41 -07002445 rc = ENABLE_INPLACE_ERR_DEV;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002446 goto errout;
2447 }
2448
2449 f2fs_info = generate_f2fs_info(data.realfd);
2450 if (!f2fs_info)
2451 goto errout;
2452
2453 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2454 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2455 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2456
2457 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2458
2459 data.one_pct = data.tot_used_blocks / 100;
2460 data.cur_pct = 0;
2461 data.time_started = time(NULL);
2462 data.remaining_time = -1;
2463
2464 data.buffer = malloc(f2fs_info->block_size);
2465 if (!data.buffer) {
2466 SLOGE("Failed to allocate crypto buffer");
2467 goto errout;
2468 }
2469
2470 data.count = 0;
2471
2472 /* Currently, this either runs to completion, or hits a nonrecoverable error */
2473 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2474
2475 if (rc) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002476 SLOGE("Error in running over f2fs blocks");
2477 rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002478 goto errout;
2479 }
2480
2481 *size_already_done += size;
2482 rc = 0;
2483
2484errout:
2485 if (rc)
2486 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2487
Paul Lawrence3846be12014-09-22 11:33:54 -07002488 log_progress_f2fs(0, true);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002489 free(f2fs_info);
2490 free(data.buffer);
2491 close(data.realfd);
2492 close(data.cryptofd);
2493
2494 return rc;
2495}
2496
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002497static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2498 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002499 off64_t tot_size,
2500 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002501{
2502 int realfd, cryptofd;
2503 char *buf[CRYPT_INPLACE_BUFSIZE];
JP Abgrall7fc1de82014-10-10 18:43:41 -07002504 int rc = ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002505 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002506 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002507 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002508
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002509 if ( (realfd = open(real_blkdev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002510 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002511 return ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002512 }
2513
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002514 if ( (cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002515 SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
2516 crypto_blkdev, errno, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002517 close(realfd);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002518 return ENABLE_INPLACE_ERR_DEV;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002519 }
2520
2521 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2522 * The size passed in is the number of 512 byte sectors in the filesystem.
2523 * So compute the number of whole 4K blocks we should read/write,
2524 * and the remainder.
2525 */
2526 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2527 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002528 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2529 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002530
2531 SLOGE("Encrypting filesystem in place...");
2532
Paul Lawrence87999172014-02-20 12:21:31 -08002533 i = previously_encrypted_upto + 1 - *size_already_done;
2534
2535 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2536 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2537 goto errout;
2538 }
2539
2540 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2541 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2542 goto errout;
2543 }
2544
2545 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2546 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2547 SLOGE("Error reading initial sectors from real_blkdev %s for "
2548 "inplace encrypt\n", crypto_blkdev);
2549 goto errout;
2550 }
2551 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2552 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2553 "inplace encrypt\n", crypto_blkdev);
2554 goto errout;
2555 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002556 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002557 }
2558 }
2559
Ken Sumrall29d8da82011-05-18 17:20:07 -07002560 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002561 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002562 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002563 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002564 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002565 if (new_pct > cur_pct) {
2566 char buf[8];
2567
2568 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002569 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002570 property_set("vold.encrypt_progress", buf);
2571 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002572 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002573 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002574 goto errout;
2575 }
2576 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002577 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2578 goto errout;
2579 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002580 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002581 CRYPT_SECTORS_PER_BUFSIZE,
2582 i * CRYPT_SECTORS_PER_BUFSIZE);
2583 }
2584
Paul Lawrence73d7a022014-06-09 14:10:09 -07002585 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002586 SLOGE("Stopping encryption due to low battery");
2587 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2588 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002589 goto errout;
2590 }
2591 }
2592
2593 /* Do any remaining sectors */
2594 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002595 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2596 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002597 goto errout;
2598 }
Paul Lawrence87999172014-02-20 12:21:31 -08002599 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2600 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002601 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002602 } else {
2603 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002604 }
2605 }
2606
Ken Sumrall29d8da82011-05-18 17:20:07 -07002607 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002608 rc = 0;
2609
2610errout:
2611 close(realfd);
2612 close(cryptofd);
2613
2614 return rc;
2615}
2616
JP Abgrall7fc1de82014-10-10 18:43:41 -07002617/* returns on of the ENABLE_INPLACE_* return codes */
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002618static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2619 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002620 off64_t tot_size,
2621 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002622{
JP Abgrall7fc1de82014-10-10 18:43:41 -07002623 int rc_ext4, rc_f2fs, rc_full;
Paul Lawrence87999172014-02-20 12:21:31 -08002624 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002625 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002626 }
2627
2628 if (*size_already_done + size < previously_encrypted_upto) {
2629 *size_already_done += size;
2630 return 0;
2631 }
2632
Daniel Rosenberge82df162014-08-15 22:19:23 +00002633 /* TODO: identify filesystem type.
2634 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2635 * then we will drop down to cryptfs_enable_inplace_f2fs.
2636 * */
JP Abgrall7fc1de82014-10-10 18:43:41 -07002637 if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002638 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002639 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002640 return 0;
2641 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002642 SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002643
JP Abgrall7fc1de82014-10-10 18:43:41 -07002644 if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002645 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002646 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002647 return 0;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002648 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002649 SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002650
JP Abgrall7fc1de82014-10-10 18:43:41 -07002651 rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002652 size, size_already_done, tot_size,
2653 previously_encrypted_upto);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002654 SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
2655
2656 /* Hack for b/17898962, the following is the symptom... */
2657 if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
2658 && rc_f2fs == ENABLE_INPLACE_ERR_DEV
2659 && rc_full == ENABLE_INPLACE_ERR_DEV) {
2660 return ENABLE_INPLACE_ERR_DEV;
2661 }
2662 return rc_full;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002663}
2664
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002665#define CRYPTO_ENABLE_WIPE 1
2666#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002667
2668#define FRAMEWORK_BOOT_WAIT 60
2669
Paul Lawrence87999172014-02-20 12:21:31 -08002670static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2671{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002672 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002673 if (fd == -1) {
2674 SLOGE("Error opening file %s", filename);
2675 return -1;
2676 }
2677
2678 char block[CRYPT_INPLACE_BUFSIZE];
2679 memset(block, 0, sizeof(block));
2680 if (unix_read(fd, block, sizeof(block)) < 0) {
2681 SLOGE("Error reading file %s", filename);
2682 close(fd);
2683 return -1;
2684 }
2685
2686 close(fd);
2687
2688 SHA256_CTX c;
2689 SHA256_Init(&c);
2690 SHA256_Update(&c, block, sizeof(block));
2691 SHA256_Final(buf, &c);
2692
2693 return 0;
2694}
2695
JP Abgrall62c7af32014-06-16 13:01:23 -07002696static int get_fs_type(struct fstab_rec *rec)
2697{
2698 if (!strcmp(rec->fs_type, "ext4")) {
2699 return EXT4_FS;
2700 } else if (!strcmp(rec->fs_type, "f2fs")) {
2701 return F2FS_FS;
2702 } else {
2703 return -1;
2704 }
2705}
2706
Paul Lawrence87999172014-02-20 12:21:31 -08002707static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2708 char *crypto_blkdev, char *real_blkdev,
2709 int previously_encrypted_upto)
2710{
2711 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002712 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002713
Paul Lawrence73d7a022014-06-09 14:10:09 -07002714 if (!is_battery_ok_to_start()) {
2715 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002716 return 0;
2717 }
2718
2719 /* The size of the userdata partition, and add in the vold volumes below */
2720 tot_encryption_size = crypt_ftr->fs_size;
2721
2722 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002723 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2724 int fs_type = get_fs_type(rec);
2725 if (fs_type < 0) {
2726 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2727 return -1;
2728 }
2729 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002730 } else if (how == CRYPTO_ENABLE_INPLACE) {
2731 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2732 crypt_ftr->fs_size, &cur_encryption_done,
2733 tot_encryption_size,
2734 previously_encrypted_upto);
2735
JP Abgrall7fc1de82014-10-10 18:43:41 -07002736 if (rc == ENABLE_INPLACE_ERR_DEV) {
2737 /* Hack for b/17898962 */
2738 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2739 cryptfs_reboot(reboot);
2740 }
2741
Paul Lawrence73d7a022014-06-09 14:10:09 -07002742 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002743 crypt_ftr->encrypted_upto = cur_encryption_done;
2744 }
2745
Paul Lawrence73d7a022014-06-09 14:10:09 -07002746 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002747 /* The inplace routine never actually sets the progress to 100% due
2748 * to the round down nature of integer division, so set it here */
2749 property_set("vold.encrypt_progress", "100");
2750 }
2751 } else {
2752 /* Shouldn't happen */
2753 SLOGE("cryptfs_enable: internal error, unknown option\n");
2754 rc = -1;
2755 }
2756
2757 return rc;
2758}
2759
Paul Lawrence13486032014-02-03 13:28:11 -08002760int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
2761 int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002762{
2763 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002764 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002765 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002766 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002767 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002768 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002769 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002770 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002771 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002772 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002773 off64_t previously_encrypted_upto = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002774
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002775 if (!strcmp(howarg, "wipe")) {
2776 how = CRYPTO_ENABLE_WIPE;
2777 } else if (! strcmp(howarg, "inplace")) {
2778 how = CRYPTO_ENABLE_INPLACE;
2779 } else {
2780 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002781 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002782 }
2783
Paul Lawrence87999172014-02-20 12:21:31 -08002784 /* See if an encryption was underway and interrupted */
2785 if (how == CRYPTO_ENABLE_INPLACE
2786 && get_crypt_ftr_and_key(&crypt_ftr) == 0
2787 && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
2788 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2789 crypt_ftr.encrypted_upto = 0;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002790 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
2791
2792 /* At this point, we are in an inconsistent state. Until we successfully
2793 complete encryption, a reboot will leave us broken. So mark the
2794 encryption failed in case that happens.
2795 On successfully completing encryption, remove this flag */
2796 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2797
2798 put_crypt_ftr_and_key(&crypt_ftr);
Paul Lawrence87999172014-02-20 12:21:31 -08002799 }
2800
2801 property_get("ro.crypto.state", encrypted_state, "");
2802 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2803 SLOGE("Device is already running encrypted, aborting");
2804 goto error_unencrypted;
2805 }
2806
2807 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2808 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002809 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002810
Ken Sumrall3ed82362011-01-28 23:31:16 -08002811 /* Get the size of the real block device */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002812 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002813 if (fd == -1) {
2814 SLOGE("Cannot open block device %s\n", real_blkdev);
2815 goto error_unencrypted;
2816 }
2817 unsigned long nr_sec;
2818 get_blkdev_size(fd, &nr_sec);
2819 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002820 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2821 goto error_unencrypted;
2822 }
2823 close(fd);
2824
2825 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002826 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002827 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002828 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002829 if (fs_size_sec == 0)
2830 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2831
Paul Lawrence87999172014-02-20 12:21:31 -08002832 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002833
2834 if (fs_size_sec > max_fs_size_sec) {
2835 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2836 goto error_unencrypted;
2837 }
2838 }
2839
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002840 /* Get a wakelock as this may take a while, and we don't want the
2841 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2842 * wants to keep the screen on, it can grab a full wakelock.
2843 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002844 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002845 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2846
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002847 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002848 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002849 */
2850 property_set("vold.decrypt", "trigger_shutdown_framework");
2851 SLOGD("Just asked init to shut down class main\n");
2852
Jeff Sharkey9c484982015-03-31 10:35:33 -07002853 /* Ask vold to unmount all devices that it manages */
2854 if (vold_unmountAll()) {
2855 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002856 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002857
2858 /* Now unmount the /data partition. */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07002859 if (wait_and_unmount(DATA_MNT_POINT, false)) {
JP Abgrall502dc742013-11-01 13:06:20 -07002860 if (allow_reboot) {
2861 goto error_shutting_down;
2862 } else {
2863 goto error_unencrypted;
2864 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002865 }
2866
2867 /* Do extra work for a better UX when doing the long inplace encryption */
2868 if (how == CRYPTO_ENABLE_INPLACE) {
2869 /* Now that /data is unmounted, we need to mount a tmpfs
2870 * /data, set a property saying we're doing inplace encryption,
2871 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002872 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002873 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002874 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002875 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002876 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002877 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002878
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002879 /* restart the framework. */
2880 /* Create necessary paths on /data */
2881 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002882 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002883 }
2884
Ken Sumrall92736ef2012-10-17 20:57:14 -07002885 /* Ugh, shutting down the framework is not synchronous, so until it
2886 * can be fixed, this horrible hack will wait a moment for it all to
2887 * shut down before proceeding. Without it, some devices cannot
2888 * restart the graphics services.
2889 */
2890 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002891 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002892
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002893 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002894 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence87999172014-02-20 12:21:31 -08002895 if (previously_encrypted_upto == 0) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002896 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2897 goto error_shutting_down;
2898 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002899
Paul Lawrence87999172014-02-20 12:21:31 -08002900 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2901 crypt_ftr.fs_size = nr_sec
2902 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2903 } else {
2904 crypt_ftr.fs_size = nr_sec;
2905 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002906 /* At this point, we are in an inconsistent state. Until we successfully
2907 complete encryption, a reboot will leave us broken. So mark the
2908 encryption failed in case that happens.
2909 On successfully completing encryption, remove this flag */
2910 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence87999172014-02-20 12:21:31 -08002911 crypt_ftr.crypt_type = crypt_type;
Ajay Dudani87701e22014-09-17 21:02:52 -07002912#ifndef CONFIG_HW_DISK_ENCRYPTION
2913 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
2914#else
2915 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-xts", MAX_CRYPTO_TYPE_NAME_LEN);
2916
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08002917 rc = clear_hw_device_encryption_key();
Ajay Dudani87701e22014-09-17 21:02:52 -07002918 if (!rc) {
2919 SLOGE("Error clearing device encryption hardware key. rc = %d", rc);
2920 }
2921
2922 rc = set_hw_device_encryption_key(passwd,
2923 (char*) crypt_ftr.crypto_type_name);
2924 if (!rc) {
2925 SLOGE("Error initializing device encryption hardware key. rc = %d", rc);
2926 goto error_shutting_down;
2927 }
2928#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002929
Paul Lawrence87999172014-02-20 12:21:31 -08002930 /* Make an encrypted master key */
2931 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
2932 SLOGE("Cannot create encrypted master key\n");
2933 goto error_shutting_down;
2934 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002935
Paul Lawrence87999172014-02-20 12:21:31 -08002936 /* Write the key to the end of the partition */
2937 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002938
Paul Lawrence87999172014-02-20 12:21:31 -08002939 /* If any persistent data has been remembered, save it.
2940 * If none, create a valid empty table and save that.
2941 */
2942 if (!persist_data) {
2943 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
2944 if (pdata) {
2945 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2946 persist_data = pdata;
2947 }
2948 }
2949 if (persist_data) {
2950 save_persistent_data();
2951 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002952 }
2953
Ajay Dudani87701e22014-09-17 21:02:52 -07002954 if (how == CRYPTO_ENABLE_INPLACE) {
2955 /* startup service classes main and late_start */
2956 property_set("vold.decrypt", "trigger_restart_min_framework");
2957 SLOGD("Just triggered restart_min_framework\n");
2958
2959 /* OK, the framework is restarted and will soon be showing a
2960 * progress bar. Time to setup an encrypted mapping, and
2961 * either write a new filesystem, or encrypt in place updating
2962 * the progress bar as we work.
2963 */
2964 }
2965
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002966 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002967 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
2968 "userdata");
2969
Paul Lawrence87999172014-02-20 12:21:31 -08002970 /* If we are continuing, check checksums match */
2971 rc = 0;
2972 if (previously_encrypted_upto) {
2973 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2974 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002975
Paul Lawrence87999172014-02-20 12:21:31 -08002976 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2977 sizeof(hash_first_block)) != 0) {
2978 SLOGE("Checksums do not match - trigger wipe");
2979 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002980 }
2981 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002982
Paul Lawrence87999172014-02-20 12:21:31 -08002983 if (!rc) {
2984 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
2985 crypto_blkdev, real_blkdev,
2986 previously_encrypted_upto);
2987 }
2988
2989 /* Calculate checksum if we are not finished */
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08002990 if (!rc && how == CRYPTO_ENABLE_INPLACE
2991 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002992 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2993 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002994 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002995 SLOGE("Error calculating checksum for continuing encryption");
2996 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002997 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002998 }
2999
3000 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003001 delete_crypto_blk_dev("userdata");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003002
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003003 if (! rc) {
3004 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003005 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08003006
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003007 if (how == CRYPTO_ENABLE_INPLACE
3008 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003009 SLOGD("Encrypted up to sector %lld - will continue after reboot",
3010 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07003011 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08003012 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07003013
Paul Lawrence6bfed202014-07-28 12:47:22 -07003014 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08003015
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003016 if (how == CRYPTO_ENABLE_WIPE
3017 || crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003018 char value[PROPERTY_VALUE_MAX];
3019 property_get("ro.crypto.state", value, "");
3020 if (!strcmp(value, "")) {
3021 /* default encryption - continue first boot sequence */
3022 property_set("ro.crypto.state", "encrypted");
3023 release_wake_lock(lockid);
3024 cryptfs_check_passwd(DEFAULT_PASSWORD);
3025 cryptfs_restart_internal(1);
3026 return 0;
3027 } else {
3028 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08003029 cryptfs_reboot(reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003030 }
Paul Lawrence87999172014-02-20 12:21:31 -08003031 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003032 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Paul Lawrence87999172014-02-20 12:21:31 -08003033 cryptfs_reboot(shutdown);
3034 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003035 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003036 char value[PROPERTY_VALUE_MAX];
3037
Ken Sumrall319369a2012-06-27 16:30:18 -07003038 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003039 if (!strcmp(value, "1")) {
3040 /* wipe data if encryption failed */
3041 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
3042 mkdir("/cache/recovery", 0700);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07003043 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC|O_CLOEXEC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003044 if (fd >= 0) {
Jeff Sharkeydd1a8042014-09-24 11:46:51 -07003045 write(fd, "--wipe_data\n", strlen("--wipe_data\n") + 1);
3046 write(fd, "--reason=cryptfs_enable_internal\n", strlen("--reason=cryptfs_enable_internal\n") + 1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003047 close(fd);
3048 } else {
3049 SLOGE("could not open /cache/recovery/command\n");
3050 }
Paul Lawrence87999172014-02-20 12:21:31 -08003051 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003052 } else {
3053 /* set property to trigger dialog */
3054 property_set("vold.encrypt_progress", "error_partially_encrypted");
3055 release_wake_lock(lockid);
3056 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003057 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003058 }
3059
Ken Sumrall3ed82362011-01-28 23:31:16 -08003060 /* hrm, the encrypt step claims success, but the reboot failed.
3061 * This should not happen.
3062 * Set the property and return. Hope the framework can deal with it.
3063 */
3064 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003065 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003066 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08003067
3068error_unencrypted:
3069 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003070 if (lockid[0]) {
3071 release_wake_lock(lockid);
3072 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003073 return -1;
3074
3075error_shutting_down:
3076 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3077 * but the framework is stopped and not restarted to show the error, so it's up to
3078 * vold to restart the system.
3079 */
3080 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08003081 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003082
3083 /* shouldn't get here */
3084 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003085 if (lockid[0]) {
3086 release_wake_lock(lockid);
3087 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003088 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003089}
3090
Paul Lawrence45f10532014-04-04 18:11:56 +00003091int cryptfs_enable(char *howarg, int type, char *passwd, int allow_reboot)
Paul Lawrence13486032014-02-03 13:28:11 -08003092{
Paul Lawrence3bd36d52015-06-09 13:37:44 -07003093 return cryptfs_enable_internal(howarg, type, passwd, allow_reboot);
Paul Lawrence13486032014-02-03 13:28:11 -08003094}
3095
3096int cryptfs_enable_default(char *howarg, int allow_reboot)
3097{
3098 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
3099 DEFAULT_PASSWORD, allow_reboot);
3100}
3101
3102int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003103{
Paul Lawrence05335c32015-03-05 09:46:23 -08003104 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3105 return e4crypt_change_password(DATA_MNT_POINT, crypt_type, newpw);
3106 }
3107
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003108 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08003109 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003110
3111 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003112 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003113 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003114 return -1;
3115 }
3116
Paul Lawrencef4faa572014-01-29 13:31:03 -08003117 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3118 SLOGE("Invalid crypt_type %d", crypt_type);
3119 return -1;
3120 }
3121
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003122 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003123 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003124 SLOGE("Error getting crypt footer and key");
3125 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003126 }
3127
Paul Lawrencef4faa572014-01-29 13:31:03 -08003128 crypt_ftr.crypt_type = crypt_type;
3129
JP Abgrall933216c2015-02-11 13:44:32 -08003130 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08003131 : newpw,
3132 crypt_ftr.salt,
3133 saved_master_key,
3134 crypt_ftr.master_key,
3135 &crypt_ftr);
JP Abgrall933216c2015-02-11 13:44:32 -08003136 if (rc) {
3137 SLOGE("Encrypt master key failed: %d", rc);
3138 return -1;
3139 }
Jason parks70a4b3f2011-01-28 10:10:47 -06003140 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003141 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003142
Ajay Dudani87701e22014-09-17 21:02:52 -07003143#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08003144 if (!strcmp((char *)crypt_ftr.crypto_type_name, "aes-xts")) {
3145 if (crypt_type == CRYPT_TYPE_DEFAULT) {
3146 int rc = update_hw_device_encryption_key(DEFAULT_PASSWORD, (char*) crypt_ftr.crypto_type_name);
3147 SLOGD("Update hardware encryption key to default for crypt_type: %d. rc = %d", crypt_type, rc);
3148 if (!rc)
3149 return -1;
3150 } else {
3151 int rc = update_hw_device_encryption_key(newpw, (char*) crypt_ftr.crypto_type_name);
3152 SLOGD("Update hardware encryption key for crypt_type: %d. rc = %d", crypt_type, rc);
3153 if (!rc)
3154 return -1;
3155 }
Ajay Dudani87701e22014-09-17 21:02:52 -07003156 }
3157#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003158 return 0;
3159}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003160
Rubin Xu85c01f92014-10-13 12:49:54 +01003161static unsigned int persist_get_max_entries(int encrypted) {
3162 struct crypt_mnt_ftr crypt_ftr;
3163 unsigned int dsize;
3164 unsigned int max_persistent_entries;
3165
3166 /* If encrypted, use the values from the crypt_ftr, otherwise
3167 * use the values for the current spec.
3168 */
3169 if (encrypted) {
3170 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3171 return -1;
3172 }
3173 dsize = crypt_ftr.persist_data_size;
3174 } else {
3175 dsize = CRYPT_PERSIST_DATA_SIZE;
3176 }
3177
3178 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3179 sizeof(struct crypt_persist_entry);
3180
3181 return max_persistent_entries;
3182}
3183
3184static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003185{
3186 unsigned int i;
3187
3188 if (persist_data == NULL) {
3189 return -1;
3190 }
3191 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3192 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3193 /* We found it! */
3194 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3195 return 0;
3196 }
3197 }
3198
3199 return -1;
3200}
3201
Rubin Xu85c01f92014-10-13 12:49:54 +01003202static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003203{
3204 unsigned int i;
3205 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003206 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003207
3208 if (persist_data == NULL) {
3209 return -1;
3210 }
3211
Rubin Xu85c01f92014-10-13 12:49:54 +01003212 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003213
3214 num = persist_data->persist_valid_entries;
3215
3216 for (i = 0; i < num; i++) {
3217 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3218 /* We found an existing entry, update it! */
3219 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3220 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3221 return 0;
3222 }
3223 }
3224
3225 /* We didn't find it, add it to the end, if there is room */
3226 if (persist_data->persist_valid_entries < max_persistent_entries) {
3227 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3228 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3229 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3230 persist_data->persist_valid_entries++;
3231 return 0;
3232 }
3233
3234 return -1;
3235}
3236
Rubin Xu85c01f92014-10-13 12:49:54 +01003237/**
3238 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3239 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3240 */
3241static int match_multi_entry(const char *key, const char *field, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003242 unsigned int field_len;
3243 unsigned int key_index;
3244 field_len = strlen(field);
3245
3246 if (index == 0) {
3247 // The first key in a multi-entry field is just the filedname itself.
3248 if (!strcmp(key, field)) {
3249 return 1;
3250 }
3251 }
3252 // Match key against "%s_%d" % (field, index)
3253 if (strlen(key) < field_len + 1 + 1) {
3254 // Need at least a '_' and a digit.
3255 return 0;
3256 }
3257 if (strncmp(key, field, field_len)) {
3258 // If the key does not begin with field, it's not a match.
3259 return 0;
3260 }
3261 if (1 != sscanf(&key[field_len],"_%d", &key_index)) {
3262 return 0;
3263 }
3264 return key_index >= index;
3265}
3266
3267/*
3268 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3269 * remaining entries starting from index will be deleted.
3270 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3271 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3272 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3273 *
3274 */
3275static int persist_del_keys(const char *fieldname, unsigned index)
3276{
3277 unsigned int i;
3278 unsigned int j;
3279 unsigned int num;
3280
3281 if (persist_data == NULL) {
3282 return PERSIST_DEL_KEY_ERROR_OTHER;
3283 }
3284
3285 num = persist_data->persist_valid_entries;
3286
3287 j = 0; // points to the end of non-deleted entries.
3288 // Filter out to-be-deleted entries in place.
3289 for (i = 0; i < num; i++) {
3290 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3291 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3292 j++;
3293 }
3294 }
3295
3296 if (j < num) {
3297 persist_data->persist_valid_entries = j;
3298 // Zeroise the remaining entries
3299 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3300 return PERSIST_DEL_KEY_OK;
3301 } else {
3302 // Did not find an entry matching the given fieldname
3303 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3304 }
3305}
3306
3307static int persist_count_keys(const char *fieldname)
3308{
3309 unsigned int i;
3310 unsigned int count;
3311
3312 if (persist_data == NULL) {
3313 return -1;
3314 }
3315
3316 count = 0;
3317 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3318 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3319 count++;
3320 }
3321 }
3322
3323 return count;
3324}
3325
Ken Sumrall160b4d62013-04-22 12:15:39 -07003326/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003327int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003328{
Paul Lawrence368d7942015-04-15 14:12:00 -07003329 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3330 return e4crypt_get_field(DATA_MNT_POINT, fieldname, value, len);
3331 }
3332
Ken Sumrall160b4d62013-04-22 12:15:39 -07003333 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003334 /* CRYPTO_GETFIELD_OK is success,
3335 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3336 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3337 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003338 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003339 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3340 int i;
3341 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003342
3343 if (persist_data == NULL) {
3344 load_persistent_data();
3345 if (persist_data == NULL) {
3346 SLOGE("Getfield error, cannot load persistent data");
3347 goto out;
3348 }
3349 }
3350
Rubin Xu85c01f92014-10-13 12:49:54 +01003351 // Read value from persistent entries. If the original value is split into multiple entries,
3352 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003353 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003354 // We found it, copy it to the caller's buffer and keep going until all entries are read.
3355 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
3356 // value too small
3357 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3358 goto out;
3359 }
3360 rc = CRYPTO_GETFIELD_OK;
3361
3362 for (i = 1; /* break explicitly */; i++) {
3363 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
3364 (int) sizeof(temp_field)) {
3365 // If the fieldname is very long, we stop as soon as it begins to overflow the
3366 // maximum field length. At this point we have in fact fully read out the original
3367 // value because cryptfs_setfield would not allow fields with longer names to be
3368 // written in the first place.
3369 break;
3370 }
3371 if (!persist_get_key(temp_field, temp_value)) {
3372 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3373 // value too small.
3374 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3375 goto out;
3376 }
3377 } else {
3378 // Exhaust all entries.
3379 break;
3380 }
3381 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003382 } else {
3383 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003384 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003385 }
3386
3387out:
3388 return rc;
3389}
3390
3391/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003392int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003393{
Paul Lawrence368d7942015-04-15 14:12:00 -07003394 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3395 return e4crypt_set_field(DATA_MNT_POINT, fieldname, value);
3396 }
3397
Ken Sumrall160b4d62013-04-22 12:15:39 -07003398 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003399 /* 0 is success, negative values are error */
3400 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003401 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003402 unsigned int field_id;
3403 char temp_field[PROPERTY_KEY_MAX];
3404 unsigned int num_entries;
3405 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003406
3407 if (persist_data == NULL) {
3408 load_persistent_data();
3409 if (persist_data == NULL) {
3410 SLOGE("Setfield error, cannot load persistent data");
3411 goto out;
3412 }
3413 }
3414
3415 property_get("ro.crypto.state", encrypted_state, "");
3416 if (!strcmp(encrypted_state, "encrypted") ) {
3417 encrypted = 1;
3418 }
3419
Rubin Xu85c01f92014-10-13 12:49:54 +01003420 // Compute the number of entries required to store value, each entry can store up to
3421 // (PROPERTY_VALUE_MAX - 1) chars
3422 if (strlen(value) == 0) {
3423 // Empty value also needs one entry to store.
3424 num_entries = 1;
3425 } else {
3426 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3427 }
3428
3429 max_keylen = strlen(fieldname);
3430 if (num_entries > 1) {
3431 // Need an extra "_%d" suffix.
3432 max_keylen += 1 + log10(num_entries);
3433 }
3434 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3435 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003436 goto out;
3437 }
3438
Rubin Xu85c01f92014-10-13 12:49:54 +01003439 // Make sure we have enough space to write the new value
3440 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3441 persist_get_max_entries(encrypted)) {
3442 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3443 goto out;
3444 }
3445
3446 // Now that we know persist_data has enough space for value, let's delete the old field first
3447 // to make up space.
3448 persist_del_keys(fieldname, 0);
3449
3450 if (persist_set_key(fieldname, value, encrypted)) {
3451 // fail to set key, should not happen as we have already checked the available space
3452 SLOGE("persist_set_key() error during setfield()");
3453 goto out;
3454 }
3455
3456 for (field_id = 1; field_id < num_entries; field_id++) {
3457 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
3458
3459 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3460 // fail to set key, should not happen as we have already checked the available space.
3461 SLOGE("persist_set_key() error during setfield()");
3462 goto out;
3463 }
3464 }
3465
Ken Sumrall160b4d62013-04-22 12:15:39 -07003466 /* If we are running encrypted, save the persistent data now */
3467 if (encrypted) {
3468 if (save_persistent_data()) {
3469 SLOGE("Setfield error, cannot save persistent data");
3470 goto out;
3471 }
3472 }
3473
Rubin Xu85c01f92014-10-13 12:49:54 +01003474 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003475
3476out:
3477 return rc;
3478}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003479
3480/* Checks userdata. Attempt to mount the volume if default-
3481 * encrypted.
3482 * On success trigger next init phase and return 0.
3483 * Currently do not handle failure - see TODO below.
3484 */
3485int cryptfs_mount_default_encrypted(void)
3486{
3487 char decrypt_state[PROPERTY_VALUE_MAX];
3488 property_get("vold.decrypt", decrypt_state, "0");
3489 if (!strcmp(decrypt_state, "0")) {
3490 SLOGE("Not encrypted - should not call here");
3491 } else {
3492 int crypt_type = cryptfs_get_password_type();
3493 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3494 SLOGE("Bad crypt type - error");
3495 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3496 SLOGD("Password is not default - "
3497 "starting min framework to prompt");
3498 property_set("vold.decrypt", "trigger_restart_min_framework");
3499 return 0;
3500 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3501 SLOGD("Password is default - restarting filesystem");
3502 cryptfs_restart_internal(0);
3503 return 0;
3504 } else {
3505 SLOGE("Encrypted, default crypt type but can't decrypt");
3506 }
3507 }
3508
Paul Lawrence6bfed202014-07-28 12:47:22 -07003509 /** Corrupt. Allow us to boot into framework, which will detect bad
3510 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003511 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003512 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003513 return 0;
3514}
3515
3516/* Returns type of the password, default, pattern, pin or password.
3517 */
3518int cryptfs_get_password_type(void)
3519{
Paul Lawrence05335c32015-03-05 09:46:23 -08003520 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3521 return e4crypt_get_password_type(DATA_MNT_POINT);
3522 }
3523
Paul Lawrencef4faa572014-01-29 13:31:03 -08003524 struct crypt_mnt_ftr crypt_ftr;
3525
3526 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3527 SLOGE("Error getting crypt footer and key\n");
3528 return -1;
3529 }
3530
Paul Lawrence6bfed202014-07-28 12:47:22 -07003531 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3532 return -1;
3533 }
3534
Paul Lawrencef4faa572014-01-29 13:31:03 -08003535 return crypt_ftr.crypt_type;
3536}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003537
Paul Lawrence05335c32015-03-05 09:46:23 -08003538const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003539{
Paul Lawrence05335c32015-03-05 09:46:23 -08003540 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3541 return e4crypt_get_password(DATA_MNT_POINT);
3542 }
3543
Paul Lawrence399317e2014-03-10 13:20:50 -07003544 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003545 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003546 if (now.tv_sec < password_expiry_time) {
3547 return password;
3548 } else {
3549 cryptfs_clear_password();
3550 return 0;
3551 }
3552}
3553
3554void cryptfs_clear_password()
3555{
Paul Lawrence86c942a2015-05-06 13:53:43 -07003556 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3557 e4crypt_clear_password(DATA_MNT_POINT);
3558 }
3559
Paul Lawrence399317e2014-03-10 13:20:50 -07003560 if (password) {
3561 size_t len = strlen(password);
3562 memset(password, 0, len);
3563 free(password);
3564 password = 0;
3565 password_expiry_time = 0;
3566 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003567}
Paul Lawrence731a7a22015-04-28 22:14:15 +00003568
3569int cryptfs_enable_file()
3570{
3571 return e4crypt_enable(DATA_MNT_POINT);
3572}
3573
3574int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3575{
3576 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3577 SLOGE("Failed to initialize crypt_ftr");
3578 return -1;
3579 }
3580
3581 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3582 crypt_ftr->salt, crypt_ftr)) {
3583 SLOGE("Cannot create encrypted master key\n");
3584 return -1;
3585 }
3586
3587 //crypt_ftr->keysize = key_length / 8;
3588 return 0;
3589}
3590
3591int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3592 unsigned char* master_key)
3593{
3594 int rc;
3595
Paul Lawrence731a7a22015-04-28 22:14:15 +00003596 unsigned char* intermediate_key = 0;
3597 size_t intermediate_key_size = 0;
Paul Lawrencec78c71b2015-04-14 15:26:29 -07003598
3599 if (password == 0 || *password == 0) {
3600 password = DEFAULT_PASSWORD;
3601 }
3602
Paul Lawrence731a7a22015-04-28 22:14:15 +00003603 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3604 &intermediate_key_size);
3605
Paul Lawrencec78c71b2015-04-14 15:26:29 -07003606 int N = 1 << ftr->N_factor;
3607 int r = 1 << ftr->r_factor;
3608 int p = 1 << ftr->p_factor;
3609
3610 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
3611
3612 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
3613 ftr->salt, sizeof(ftr->salt), N, r, p,
3614 scrypted_intermediate_key,
3615 sizeof(scrypted_intermediate_key));
3616
3617 free(intermediate_key);
3618
3619 if (rc) {
3620 SLOGE("Can't calculate intermediate key");
3621 return rc;
3622 }
3623
3624 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
3625 intermediate_key_size);
Paul Lawrence731a7a22015-04-28 22:14:15 +00003626}
3627
3628int cryptfs_set_password(struct crypt_mnt_ftr* ftr, const char* password,
3629 const unsigned char* master_key)
3630{
3631 return encrypt_master_key(password, ftr->salt, master_key, ftr->master_key,
3632 ftr);
3633}