blob: 3d1dddd0b38ad71e8fefa4f9e8a610c48e66eec6 [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
23#include <sys/types.h>
Ken Sumralle550f782013-08-20 13:48:23 -070024#include <sys/wait.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080025#include <sys/stat.h>
Paul Lawrencef4faa572014-01-29 13:31:03 -080026#include <ctype.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080027#include <fcntl.h>
Elliott Hughes73737162014-06-25 17:27:42 -070028#include <inttypes.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080029#include <unistd.h>
30#include <stdio.h>
31#include <sys/ioctl.h>
32#include <linux/dm-ioctl.h>
33#include <libgen.h>
34#include <stdlib.h>
35#include <sys/param.h>
36#include <string.h>
37#include <sys/mount.h>
38#include <openssl/evp.h>
39#include <errno.h>
Ken Sumrall3ed82362011-01-28 23:31:16 -080040#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070041#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070042#include <fs_mgr.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080043#include "cryptfs.h"
44#define LOG_TAG "Cryptfs"
45#include "cutils/log.h"
46#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070047#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080048#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070049#include <logwrap/logwrap.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070050#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070051#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070052#include "crypto_scrypt.h"
Paul Lawrenceae59fe62014-01-21 08:23:27 -080053#include "ext4_utils.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000054#include "f2fs_sparseblock.h"
Paul Lawrence87999172014-02-20 12:21:31 -080055#include "CheckBattery.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080056
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070057#include <hardware/keymaster.h>
58
Mark Salyzyn3e971272014-01-21 13:27:04 -080059#define UNUSED __attribute__((unused))
60
Mark Salyzyn5eecc442014-02-12 14:16:14 -080061#define UNUSED __attribute__((unused))
62
Ken Sumrall8f869aa2010-12-03 03:47:09 -080063#define DM_CRYPT_BUF_SIZE 4096
64
Jason parks70a4b3f2011-01-28 10:10:47 -060065#define HASH_COUNT 2000
66#define KEY_LEN_BYTES 16
67#define IV_LEN_BYTES 16
68
Ken Sumrall29d8da82011-05-18 17:20:07 -070069#define KEY_IN_FOOTER "footer"
70
Paul Lawrencef4faa572014-01-29 13:31:03 -080071// "default_password" encoded into hex (d=0x64 etc)
72#define DEFAULT_PASSWORD "64656661756c745f70617373776f7264"
73
Ken Sumrall29d8da82011-05-18 17:20:07 -070074#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070075#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070076
Ken Sumralle919efe2012-09-29 17:07:41 -070077#define TABLE_LOAD_RETRIES 10
78
Shawn Willden47ba10d2014-09-03 17:07:06 -060079#define RSA_KEY_SIZE 2048
80#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
81#define RSA_EXPONENT 0x10001
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070082
Paul Lawrence8e3f4512014-09-08 10:11:17 -070083#define RETRY_MOUNT_ATTEMPTS 10
84#define RETRY_MOUNT_DELAY_SECONDS 1
85
Ken Sumrall8f869aa2010-12-03 03:47:09 -080086char *me = "cryptfs";
87
Jason parks70a4b3f2011-01-28 10:10:47 -060088static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070089static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060090static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -070091static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -080092
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070093static int keymaster_init(keymaster_device_t **keymaster_dev)
94{
95 int rc;
96
97 const hw_module_t* mod;
98 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
99 if (rc) {
100 ALOGE("could not find any keystore module");
101 goto out;
102 }
103
104 rc = keymaster_open(mod, keymaster_dev);
105 if (rc) {
106 ALOGE("could not open keymaster device in %s (%s)",
107 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
108 goto out;
109 }
110
111 return 0;
112
113out:
114 *keymaster_dev = NULL;
115 return rc;
116}
117
118/* Should we use keymaster? */
119static int keymaster_check_compatibility()
120{
121 keymaster_device_t *keymaster_dev = 0;
122 int rc = 0;
123
124 if (keymaster_init(&keymaster_dev)) {
125 SLOGE("Failed to init keymaster");
126 rc = -1;
127 goto out;
128 }
129
Paul Lawrence8c008392014-05-06 14:02:48 -0700130 SLOGI("keymaster version is %d", keymaster_dev->common.module->module_api_version);
131
132 if (keymaster_dev->common.module->module_api_version
133 < KEYMASTER_MODULE_API_VERSION_0_3) {
134 rc = 0;
135 goto out;
136 }
137
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700138 if (keymaster_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE) {
139 rc = 1;
140 }
141
142out:
143 keymaster_close(keymaster_dev);
144 return rc;
145}
146
147/* Create a new keymaster key and store it in this footer */
148static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
149{
150 uint8_t* key = 0;
151 keymaster_device_t *keymaster_dev = 0;
152
153 if (keymaster_init(&keymaster_dev)) {
154 SLOGE("Failed to init keymaster");
155 return -1;
156 }
157
158 int rc = 0;
159
160 keymaster_rsa_keygen_params_t params;
161 memset(&params, '\0', sizeof(params));
Shawn Willden47ba10d2014-09-03 17:07:06 -0600162 params.public_exponent = RSA_EXPONENT;
163 params.modulus_size = RSA_KEY_SIZE;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700164
165 size_t key_size;
166 if (keymaster_dev->generate_keypair(keymaster_dev, TYPE_RSA, &params,
167 &key, &key_size)) {
168 SLOGE("Failed to generate keypair");
169 rc = -1;
170 goto out;
171 }
172
173 if (key_size > KEYMASTER_BLOB_SIZE) {
174 SLOGE("Keymaster key too large for crypto footer");
175 rc = -1;
176 goto out;
177 }
178
179 memcpy(ftr->keymaster_blob, key, key_size);
180 ftr->keymaster_blob_size = key_size;
181
182out:
183 keymaster_close(keymaster_dev);
184 free(key);
185 return rc;
186}
187
Shawn Willdene17a9c42014-09-08 13:04:08 -0600188/* This signs the given object using the keymaster key. */
189static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600190 const unsigned char *object,
191 const size_t object_size,
192 unsigned char **signature,
193 size_t *signature_size)
194{
195 int rc = 0;
196 keymaster_device_t *keymaster_dev = 0;
197 if (keymaster_init(&keymaster_dev)) {
198 SLOGE("Failed to init keymaster");
199 return -1;
200 }
201
202 /* We currently set the digest type to DIGEST_NONE because it's the
203 * only supported value for keymaster. A similar issue exists with
204 * PADDING_NONE. Long term both of these should likely change.
205 */
206 keymaster_rsa_sign_params_t params;
207 params.digest_type = DIGEST_NONE;
208 params.padding_type = PADDING_NONE;
209
210 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600211 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600212 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600213
Shawn Willdene17a9c42014-09-08 13:04:08 -0600214 // To sign a message with RSA, the message must satisfy two
215 // constraints:
216 //
217 // 1. The message, when interpreted as a big-endian numeric value, must
218 // be strictly less than the public modulus of the RSA key. Note
219 // that because the most significant bit of the public modulus is
220 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
221 // key), an n-bit message with most significant bit 0 always
222 // satisfies this requirement.
223 //
224 // 2. The message must have the same length in bits as the public
225 // modulus of the RSA key. This requirement isn't mathematically
226 // necessary, but is necessary to ensure consistency in
227 // implementations.
228 switch (ftr->kdf_type) {
229 case KDF_SCRYPT_KEYMASTER_UNPADDED:
230 // This is broken: It produces a message which is shorter than
231 // the public modulus, failing criterion 2.
232 memcpy(to_sign, object, object_size);
233 to_sign_size = object_size;
234 SLOGI("Signing unpadded object");
235 break;
236 case KDF_SCRYPT_KEYMASTER_BADLY_PADDED:
237 // This is broken: Since the value of object is uniformly
238 // distributed, it produces a message that is larger than the
239 // public modulus with probability 0.25.
240 memcpy(to_sign, object, min(RSA_KEY_SIZE_BYTES, object_size));
241 SLOGI("Signing end-padded object");
242 break;
243 case KDF_SCRYPT_KEYMASTER:
244 // This ensures the most significant byte of the signed message
245 // is zero. We could have zero-padded to the left instead, but
246 // this approach is slightly more robust against changes in
247 // object size. However, it's still broken (but not unusably
248 // so) because we really should be using a proper RSA padding
249 // function, such as OAEP.
250 //
251 // TODO(paullawrence): When keymaster 0.4 is available, change
252 // this to use the padding options it provides.
253 memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
254 SLOGI("Signing safely-padded object");
255 break;
256 default:
257 SLOGE("Unknown KDF type %d", ftr->kdf_type);
258 return -1;
259 }
260
Shawn Willden47ba10d2014-09-03 17:07:06 -0600261 rc = keymaster_dev->sign_data(keymaster_dev,
262 &params,
263 ftr->keymaster_blob,
264 ftr->keymaster_blob_size,
265 to_sign,
Shawn Willdene17a9c42014-09-08 13:04:08 -0600266 to_sign_size,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600267 signature,
268 signature_size);
269
270 keymaster_close(keymaster_dev);
271 return rc;
272}
273
Paul Lawrence399317e2014-03-10 13:20:50 -0700274/* Store password when userdata is successfully decrypted and mounted.
275 * Cleared by cryptfs_clear_password
276 *
277 * To avoid a double prompt at boot, we need to store the CryptKeeper
278 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
279 * Since the entire framework is torn down and rebuilt after encryption,
280 * we have to use a daemon or similar to store the password. Since vold
281 * is secured against IPC except from system processes, it seems a reasonable
282 * place to store this.
283 *
284 * password should be cleared once it has been used.
285 *
286 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800287 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700288static char* password = 0;
289static int password_expiry_time = 0;
290static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800291
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800292extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800293
Paul Lawrence87999172014-02-20 12:21:31 -0800294enum RebootType {reboot, recovery, shutdown};
295static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700296{
Paul Lawrence87999172014-02-20 12:21:31 -0800297 switch(rt) {
298 case reboot:
299 property_set(ANDROID_RB_PROPERTY, "reboot");
300 break;
301
302 case recovery:
303 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
304 break;
305
306 case shutdown:
307 property_set(ANDROID_RB_PROPERTY, "shutdown");
308 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700309 }
Paul Lawrence87999172014-02-20 12:21:31 -0800310
Ken Sumralladfba362013-06-04 16:37:52 -0700311 sleep(20);
312
313 /* Shouldn't get here, reboot should happen before sleep times out */
314 return;
315}
316
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800317static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
318{
319 memset(io, 0, dataSize);
320 io->data_size = dataSize;
321 io->data_start = sizeof(struct dm_ioctl);
322 io->version[0] = 4;
323 io->version[1] = 0;
324 io->version[2] = 0;
325 io->flags = flags;
326 if (name) {
327 strncpy(io->name, name, sizeof(io->name));
328 }
329}
330
Kenny Rootc4c70f12013-06-14 12:11:38 -0700331/**
332 * Gets the default device scrypt parameters for key derivation time tuning.
333 * The parameters should lead to about one second derivation time for the
334 * given device.
335 */
336static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
337 const int default_params[] = SCRYPT_DEFAULTS;
338 int params[] = SCRYPT_DEFAULTS;
339 char paramstr[PROPERTY_VALUE_MAX];
340 char *token;
341 char *saveptr;
342 int i;
343
344 property_get(SCRYPT_PROP, paramstr, "");
345 if (paramstr[0] != '\0') {
346 /*
347 * The token we're looking for should be three integers separated by
348 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
349 */
Kenny Root2947e342013-08-14 15:54:49 -0700350 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
351 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700352 i++, token = strtok_r(NULL, ":", &saveptr)) {
353 char *endptr;
354 params[i] = strtol(token, &endptr, 10);
355
356 /*
357 * Check that there was a valid number and it's 8-bit. If not,
358 * break out and the end check will take the default values.
359 */
360 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
361 break;
362 }
363 }
364
365 /*
366 * If there were not enough tokens or a token was malformed (not an
367 * integer), it will end up here and the default parameters can be
368 * taken.
369 */
370 if ((i != 3) || (token != NULL)) {
371 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
372 memcpy(params, default_params, sizeof(params));
373 }
374 }
375
376 ftr->N_factor = params[0];
377 ftr->r_factor = params[1];
378 ftr->p_factor = params[2];
379}
380
Ken Sumrall3ed82362011-01-28 23:31:16 -0800381static unsigned int get_fs_size(char *dev)
382{
383 int fd, block_size;
384 struct ext4_super_block sb;
385 off64_t len;
386
387 if ((fd = open(dev, O_RDONLY)) < 0) {
388 SLOGE("Cannot open device to get filesystem size ");
389 return 0;
390 }
391
392 if (lseek64(fd, 1024, SEEK_SET) < 0) {
393 SLOGE("Cannot seek to superblock");
394 return 0;
395 }
396
397 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
398 SLOGE("Cannot read superblock");
399 return 0;
400 }
401
402 close(fd);
403
Daniel Rosenberge82df162014-08-15 22:19:23 +0000404 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
405 SLOGE("Not a valid ext4 superblock");
406 return 0;
407 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800408 block_size = 1024 << sb.s_log_block_size;
409 /* compute length in bytes */
410 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
411
412 /* return length in sectors */
413 return (unsigned int) (len / 512);
414}
415
Ken Sumrall160b4d62013-04-22 12:15:39 -0700416static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
417{
418 static int cached_data = 0;
419 static off64_t cached_off = 0;
420 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
421 int fd;
422 char key_loc[PROPERTY_VALUE_MAX];
423 char real_blkdev[PROPERTY_VALUE_MAX];
424 unsigned int nr_sec;
425 int rc = -1;
426
427 if (!cached_data) {
428 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
429
430 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
431 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
432 SLOGE("Cannot open real block device %s\n", real_blkdev);
433 return -1;
434 }
435
436 if ((nr_sec = get_blkdev_size(fd))) {
437 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
438 * encryption info footer and key, and plenty of bytes to spare for future
439 * growth.
440 */
441 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
442 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
443 cached_data = 1;
444 } else {
445 SLOGE("Cannot get size of block device %s\n", real_blkdev);
446 }
447 close(fd);
448 } else {
449 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
450 cached_off = 0;
451 cached_data = 1;
452 }
453 }
454
455 if (cached_data) {
456 if (metadata_fname) {
457 *metadata_fname = cached_metadata_fname;
458 }
459 if (off) {
460 *off = cached_off;
461 }
462 rc = 0;
463 }
464
465 return rc;
466}
467
Ken Sumralle8744072011-01-18 22:01:55 -0800468/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800469 * update the failed mount count but not change the key.
470 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700471static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800472{
473 int fd;
474 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700475 /* starting_off is set to the SEEK_SET offset
476 * where the crypto structure starts
477 */
478 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800479 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700480 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700481 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800482
Ken Sumrall160b4d62013-04-22 12:15:39 -0700483 if (get_crypt_ftr_info(&fname, &starting_off)) {
484 SLOGE("Unable to get crypt_ftr_info\n");
485 return -1;
486 }
487 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700488 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700489 return -1;
490 }
Ken Sumralle550f782013-08-20 13:48:23 -0700491 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
492 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700493 return -1;
494 }
495
496 /* Seek to the start of the crypt footer */
497 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
498 SLOGE("Cannot seek to real block device footer\n");
499 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800500 }
501
502 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
503 SLOGE("Cannot write real block device footer\n");
504 goto errout;
505 }
506
Ken Sumrall3be890f2011-09-14 16:53:46 -0700507 fstat(fd, &statbuf);
508 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700509 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700510 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800511 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800512 goto errout;
513 }
514 }
515
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800516 /* Success! */
517 rc = 0;
518
519errout:
520 close(fd);
521 return rc;
522
523}
524
Ken Sumrall160b4d62013-04-22 12:15:39 -0700525static inline int unix_read(int fd, void* buff, int len)
526{
527 return TEMP_FAILURE_RETRY(read(fd, buff, len));
528}
529
530static inline int unix_write(int fd, const void* buff, int len)
531{
532 return TEMP_FAILURE_RETRY(write(fd, buff, len));
533}
534
535static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
536{
537 memset(pdata, 0, len);
538 pdata->persist_magic = PERSIST_DATA_MAGIC;
539 pdata->persist_valid_entries = 0;
540}
541
542/* A routine to update the passed in crypt_ftr to the lastest version.
543 * fd is open read/write on the device that holds the crypto footer and persistent
544 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
545 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
546 */
547static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
548{
Kenny Root7434b312013-06-14 11:29:53 -0700549 int orig_major = crypt_ftr->major_version;
550 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700551
Kenny Root7434b312013-06-14 11:29:53 -0700552 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
553 struct crypt_persist_data *pdata;
554 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700555
Kenny Rootc4c70f12013-06-14 12:11:38 -0700556 SLOGW("upgrading crypto footer to 1.1");
557
Kenny Root7434b312013-06-14 11:29:53 -0700558 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
559 if (pdata == NULL) {
560 SLOGE("Cannot allocate persisent data\n");
561 return;
562 }
563 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
564
565 /* Need to initialize the persistent data area */
566 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
567 SLOGE("Cannot seek to persisent data offset\n");
568 return;
569 }
570 /* Write all zeros to the first copy, making it invalid */
571 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
572
573 /* Write a valid but empty structure to the second copy */
574 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
575 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
576
577 /* Update the footer */
578 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
579 crypt_ftr->persist_data_offset[0] = pdata_offset;
580 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
581 crypt_ftr->minor_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700582 }
583
Paul Lawrencef4faa572014-01-29 13:31:03 -0800584 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700585 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800586 /* But keep the old kdf_type.
587 * It will get updated later to KDF_SCRYPT after the password has been verified.
588 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700589 crypt_ftr->kdf_type = KDF_PBKDF2;
590 get_device_scrypt_params(crypt_ftr);
591 crypt_ftr->minor_version = 2;
592 }
593
Paul Lawrencef4faa572014-01-29 13:31:03 -0800594 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
595 SLOGW("upgrading crypto footer to 1.3");
596 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
597 crypt_ftr->minor_version = 3;
598 }
599
Kenny Root7434b312013-06-14 11:29:53 -0700600 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
601 if (lseek64(fd, offset, SEEK_SET) == -1) {
602 SLOGE("Cannot seek to crypt footer\n");
603 return;
604 }
605 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700606 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700607}
608
609
610static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800611{
612 int fd;
613 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700614 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800615 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700616 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700617 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800618
Ken Sumrall160b4d62013-04-22 12:15:39 -0700619 if (get_crypt_ftr_info(&fname, &starting_off)) {
620 SLOGE("Unable to get crypt_ftr_info\n");
621 return -1;
622 }
623 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700624 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700625 return -1;
626 }
627 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700628 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700629 return -1;
630 }
631
632 /* Make sure it's 16 Kbytes in length */
633 fstat(fd, &statbuf);
634 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
635 SLOGE("footer file %s is not the expected size!\n", fname);
636 goto errout;
637 }
638
639 /* Seek to the start of the crypt footer */
640 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
641 SLOGE("Cannot seek to real block device footer\n");
642 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800643 }
644
645 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
646 SLOGE("Cannot read real block device footer\n");
647 goto errout;
648 }
649
650 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700651 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800652 goto errout;
653 }
654
Kenny Rootc96a5f82013-06-14 12:08:28 -0700655 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
656 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
657 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800658 goto errout;
659 }
660
Kenny Rootc96a5f82013-06-14 12:08:28 -0700661 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
662 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
663 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800664 }
665
Ken Sumrall160b4d62013-04-22 12:15:39 -0700666 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
667 * copy on disk before returning.
668 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700669 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700670 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800671 }
672
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800673 /* Success! */
674 rc = 0;
675
676errout:
677 close(fd);
678 return rc;
679}
680
Ken Sumrall160b4d62013-04-22 12:15:39 -0700681static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
682{
683 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
684 crypt_ftr->persist_data_offset[1]) {
685 SLOGE("Crypt_ftr persist data regions overlap");
686 return -1;
687 }
688
689 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
690 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
691 return -1;
692 }
693
694 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
695 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
696 CRYPT_FOOTER_OFFSET) {
697 SLOGE("Persistent data extends past crypto footer");
698 return -1;
699 }
700
701 return 0;
702}
703
704static int load_persistent_data(void)
705{
706 struct crypt_mnt_ftr crypt_ftr;
707 struct crypt_persist_data *pdata = NULL;
708 char encrypted_state[PROPERTY_VALUE_MAX];
709 char *fname;
710 int found = 0;
711 int fd;
712 int ret;
713 int i;
714
715 if (persist_data) {
716 /* Nothing to do, we've already loaded or initialized it */
717 return 0;
718 }
719
720
721 /* If not encrypted, just allocate an empty table and initialize it */
722 property_get("ro.crypto.state", encrypted_state, "");
723 if (strcmp(encrypted_state, "encrypted") ) {
724 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
725 if (pdata) {
726 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
727 persist_data = pdata;
728 return 0;
729 }
730 return -1;
731 }
732
733 if(get_crypt_ftr_and_key(&crypt_ftr)) {
734 return -1;
735 }
736
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700737 if ((crypt_ftr.major_version < 1)
738 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700739 SLOGE("Crypt_ftr version doesn't support persistent data");
740 return -1;
741 }
742
743 if (get_crypt_ftr_info(&fname, NULL)) {
744 return -1;
745 }
746
747 ret = validate_persistent_data_storage(&crypt_ftr);
748 if (ret) {
749 return -1;
750 }
751
752 fd = open(fname, O_RDONLY);
753 if (fd < 0) {
754 SLOGE("Cannot open %s metadata file", fname);
755 return -1;
756 }
757
758 if (persist_data == NULL) {
759 pdata = malloc(crypt_ftr.persist_data_size);
760 if (pdata == NULL) {
761 SLOGE("Cannot allocate memory for persistent data");
762 goto err;
763 }
764 }
765
766 for (i = 0; i < 2; i++) {
767 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
768 SLOGE("Cannot seek to read persistent data on %s", fname);
769 goto err2;
770 }
771 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
772 SLOGE("Error reading persistent data on iteration %d", i);
773 goto err2;
774 }
775 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
776 found = 1;
777 break;
778 }
779 }
780
781 if (!found) {
782 SLOGI("Could not find valid persistent data, creating");
783 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
784 }
785
786 /* Success */
787 persist_data = pdata;
788 close(fd);
789 return 0;
790
791err2:
792 free(pdata);
793
794err:
795 close(fd);
796 return -1;
797}
798
799static int save_persistent_data(void)
800{
801 struct crypt_mnt_ftr crypt_ftr;
802 struct crypt_persist_data *pdata;
803 char *fname;
804 off64_t write_offset;
805 off64_t erase_offset;
806 int found = 0;
807 int fd;
808 int ret;
809
810 if (persist_data == NULL) {
811 SLOGE("No persistent data to save");
812 return -1;
813 }
814
815 if(get_crypt_ftr_and_key(&crypt_ftr)) {
816 return -1;
817 }
818
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700819 if ((crypt_ftr.major_version < 1)
820 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700821 SLOGE("Crypt_ftr version doesn't support persistent data");
822 return -1;
823 }
824
825 ret = validate_persistent_data_storage(&crypt_ftr);
826 if (ret) {
827 return -1;
828 }
829
830 if (get_crypt_ftr_info(&fname, NULL)) {
831 return -1;
832 }
833
834 fd = open(fname, O_RDWR);
835 if (fd < 0) {
836 SLOGE("Cannot open %s metadata file", fname);
837 return -1;
838 }
839
840 pdata = malloc(crypt_ftr.persist_data_size);
841 if (pdata == NULL) {
842 SLOGE("Cannot allocate persistant data");
843 goto err;
844 }
845
846 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
847 SLOGE("Cannot seek to read persistent data on %s", fname);
848 goto err2;
849 }
850
851 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
852 SLOGE("Error reading persistent data before save");
853 goto err2;
854 }
855
856 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
857 /* The first copy is the curent valid copy, so write to
858 * the second copy and erase this one */
859 write_offset = crypt_ftr.persist_data_offset[1];
860 erase_offset = crypt_ftr.persist_data_offset[0];
861 } else {
862 /* The second copy must be the valid copy, so write to
863 * the first copy, and erase the second */
864 write_offset = crypt_ftr.persist_data_offset[0];
865 erase_offset = crypt_ftr.persist_data_offset[1];
866 }
867
868 /* Write the new copy first, if successful, then erase the old copy */
869 if (lseek(fd, write_offset, SEEK_SET) < 0) {
870 SLOGE("Cannot seek to write persistent data");
871 goto err2;
872 }
873 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
874 (int) crypt_ftr.persist_data_size) {
875 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
876 SLOGE("Cannot seek to erase previous persistent data");
877 goto err2;
878 }
879 fsync(fd);
880 memset(pdata, 0, crypt_ftr.persist_data_size);
881 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
882 (int) crypt_ftr.persist_data_size) {
883 SLOGE("Cannot write to erase previous persistent data");
884 goto err2;
885 }
886 fsync(fd);
887 } else {
888 SLOGE("Cannot write to save persistent data");
889 goto err2;
890 }
891
892 /* Success */
893 free(pdata);
894 close(fd);
895 return 0;
896
897err2:
898 free(pdata);
899err:
900 close(fd);
901 return -1;
902}
903
Paul Lawrencef4faa572014-01-29 13:31:03 -0800904static int hexdigit (char c)
905{
906 if (c >= '0' && c <= '9') return c - '0';
907 c = tolower(c);
908 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
909 return -1;
910}
911
912static unsigned char* convert_hex_ascii_to_key(const char* master_key_ascii,
913 unsigned int* out_keysize)
914{
915 unsigned int i;
916 *out_keysize = 0;
917
918 size_t size = strlen (master_key_ascii);
919 if (size % 2) {
920 SLOGE("Trying to convert ascii string of odd length");
921 return NULL;
922 }
923
924 unsigned char* master_key = (unsigned char*) malloc(size / 2);
925 if (master_key == 0) {
926 SLOGE("Cannot allocate");
927 return NULL;
928 }
929
930 for (i = 0; i < size; i += 2) {
931 int high_nibble = hexdigit (master_key_ascii[i]);
932 int low_nibble = hexdigit (master_key_ascii[i + 1]);
933
934 if(high_nibble < 0 || low_nibble < 0) {
935 SLOGE("Invalid hex string");
936 free (master_key);
937 return NULL;
938 }
939
940 master_key[*out_keysize] = high_nibble * 16 + low_nibble;
941 (*out_keysize)++;
942 }
943
944 return master_key;
945}
946
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800947/* Convert a binary key of specified length into an ascii hex string equivalent,
948 * without the leading 0x and with null termination
949 */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800950static void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800951 char *master_key_ascii)
952{
953 unsigned int i, a;
954 unsigned char nibble;
955
956 for (i=0, a=0; i<keysize; i++, a+=2) {
957 /* For each byte, write out two ascii hex digits */
958 nibble = (master_key[i] >> 4) & 0xf;
959 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
960
961 nibble = master_key[i] & 0xf;
962 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
963 }
964
965 /* Add the null termination */
966 master_key_ascii[a] = '\0';
967
968}
969
Ken Sumralldb5e0262013-02-05 17:39:48 -0800970static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
971 char *real_blk_name, const char *name, int fd,
972 char *extra_params)
973{
974 char buffer[DM_CRYPT_BUF_SIZE];
975 struct dm_ioctl *io;
976 struct dm_target_spec *tgt;
977 char *crypt_params;
978 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
979 int i;
980
981 io = (struct dm_ioctl *) buffer;
982
983 /* Load the mapping table for this device */
984 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
985
986 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
987 io->target_count = 1;
988 tgt->status = 0;
989 tgt->sector_start = 0;
990 tgt->length = crypt_ftr->fs_size;
991 strcpy(tgt->target_type, "crypt");
992
993 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
994 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
995 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
996 master_key_ascii, real_blk_name, extra_params);
997 crypt_params += strlen(crypt_params) + 1;
998 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
999 tgt->next = crypt_params - buffer;
1000
1001 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1002 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
1003 break;
1004 }
1005 usleep(500000);
1006 }
1007
1008 if (i == TABLE_LOAD_RETRIES) {
1009 /* We failed to load the table, return an error */
1010 return -1;
1011 } else {
1012 return i + 1;
1013 }
1014}
1015
1016
1017static int get_dm_crypt_version(int fd, const char *name, int *version)
1018{
1019 char buffer[DM_CRYPT_BUF_SIZE];
1020 struct dm_ioctl *io;
1021 struct dm_target_versions *v;
1022 int i;
1023
1024 io = (struct dm_ioctl *) buffer;
1025
1026 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1027
1028 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1029 return -1;
1030 }
1031
1032 /* Iterate over the returned versions, looking for name of "crypt".
1033 * When found, get and return the version.
1034 */
1035 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1036 while (v->next) {
1037 if (! strcmp(v->name, "crypt")) {
1038 /* We found the crypt driver, return the version, and get out */
1039 version[0] = v->version[0];
1040 version[1] = v->version[1];
1041 version[2] = v->version[2];
1042 return 0;
1043 }
1044 v = (struct dm_target_versions *)(((char *)v) + v->next);
1045 }
1046
1047 return -1;
1048}
1049
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001050static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -07001051 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001052{
1053 char buffer[DM_CRYPT_BUF_SIZE];
1054 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
1055 char *crypt_params;
1056 struct dm_ioctl *io;
1057 struct dm_target_spec *tgt;
1058 unsigned int minor;
1059 int fd;
Ken Sumralle919efe2012-09-29 17:07:41 -07001060 int i;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001061 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001062 int version[3];
1063 char *extra_params;
1064 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001065
1066 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1067 SLOGE("Cannot open device-mapper\n");
1068 goto errout;
1069 }
1070
1071 io = (struct dm_ioctl *) buffer;
1072
1073 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1074 if (ioctl(fd, DM_DEV_CREATE, io)) {
1075 SLOGE("Cannot create dm-crypt device\n");
1076 goto errout;
1077 }
1078
1079 /* Get the device status, in particular, the name of it's device file */
1080 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1081 if (ioctl(fd, DM_DEV_STATUS, io)) {
1082 SLOGE("Cannot retrieve dm-crypt device status\n");
1083 goto errout;
1084 }
1085 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1086 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1087
Ken Sumralldb5e0262013-02-05 17:39:48 -08001088 extra_params = "";
1089 if (! get_dm_crypt_version(fd, name, version)) {
1090 /* Support for allow_discards was added in version 1.11.0 */
1091 if ((version[0] >= 2) ||
1092 ((version[0] == 1) && (version[1] >= 11))) {
1093 extra_params = "1 allow_discards";
1094 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1095 }
Ken Sumralle919efe2012-09-29 17:07:41 -07001096 }
1097
Ken Sumralldb5e0262013-02-05 17:39:48 -08001098 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1099 fd, extra_params);
1100 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001101 SLOGE("Cannot load dm-crypt mapping table.\n");
1102 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001103 } else if (load_count > 1) {
1104 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001105 }
1106
1107 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -08001108 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001109
1110 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1111 SLOGE("Cannot resume the dm-crypt device\n");
1112 goto errout;
1113 }
1114
1115 /* We made it here with no errors. Woot! */
1116 retval = 0;
1117
1118errout:
1119 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1120
1121 return retval;
1122}
1123
Ken Sumrall29d8da82011-05-18 17:20:07 -07001124static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001125{
1126 int fd;
1127 char buffer[DM_CRYPT_BUF_SIZE];
1128 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001129 int retval = -1;
1130
1131 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1132 SLOGE("Cannot open device-mapper\n");
1133 goto errout;
1134 }
1135
1136 io = (struct dm_ioctl *) buffer;
1137
1138 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1139 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1140 SLOGE("Cannot remove dm-crypt device\n");
1141 goto errout;
1142 }
1143
1144 /* We made it here with no errors. Woot! */
1145 retval = 0;
1146
1147errout:
1148 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1149
1150 return retval;
1151
1152}
1153
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001154static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001155 unsigned char *ikey, void *params UNUSED)
1156{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001157 SLOGI("Using pbkdf2 for cryptfs KDF");
1158
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001159 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001160 unsigned int keysize;
1161 char* master_key = (char*)convert_hex_ascii_to_key(passwd, &keysize);
1162 if (!master_key) return -1;
1163 PKCS5_PBKDF2_HMAC_SHA1(master_key, keysize, salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001164 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001165
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001166 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001167 free (master_key);
1168 return 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001169}
1170
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001171static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001172 unsigned char *ikey, void *params)
1173{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001174 SLOGI("Using scrypt for cryptfs KDF");
1175
Kenny Rootc4c70f12013-06-14 12:11:38 -07001176 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1177
1178 int N = 1 << ftr->N_factor;
1179 int r = 1 << ftr->r_factor;
1180 int p = 1 << ftr->p_factor;
1181
1182 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001183 unsigned int keysize;
1184 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &keysize);
1185 if (!master_key) return -1;
1186 crypto_scrypt(master_key, keysize, salt, SALT_LEN, N, r, p, ikey,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001187 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001188
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001189 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001190 free (master_key);
1191 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001192}
1193
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001194static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1195 unsigned char *ikey, void *params)
1196{
1197 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1198
1199 int rc;
1200 unsigned int key_size;
1201 size_t signature_size;
1202 unsigned char* signature;
1203 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1204
1205 int N = 1 << ftr->N_factor;
1206 int r = 1 << ftr->r_factor;
1207 int p = 1 << ftr->p_factor;
1208
1209 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &key_size);
1210 if (!master_key) {
1211 SLOGE("Failed to convert passwd from hex");
1212 return -1;
1213 }
1214
1215 rc = crypto_scrypt(master_key, key_size, salt, SALT_LEN,
1216 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1217 memset(master_key, 0, key_size);
1218 free(master_key);
1219
1220 if (rc) {
1221 SLOGE("scrypt failed");
1222 return -1;
1223 }
1224
Shawn Willdene17a9c42014-09-08 13:04:08 -06001225 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1226 &signature, &signature_size)) {
1227 SLOGE("Signing failed");
1228 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001229 }
1230
1231 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1232 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1233 free(signature);
1234
1235 if (rc) {
1236 SLOGE("scrypt failed");
1237 return -1;
1238 }
1239
1240 return 0;
1241}
1242
1243static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1244 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001245 unsigned char *encrypted_master_key,
1246 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001247{
1248 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1249 EVP_CIPHER_CTX e_ctx;
1250 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001251 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001252
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001253 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001254 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001255
1256 switch (crypt_ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001257 case KDF_SCRYPT_KEYMASTER_UNPADDED:
1258 case KDF_SCRYPT_KEYMASTER_BADLY_PADDED:
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001259 case KDF_SCRYPT_KEYMASTER:
1260 if (keymaster_create_key(crypt_ftr)) {
1261 SLOGE("keymaster_create_key failed");
1262 return -1;
1263 }
1264
1265 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1266 SLOGE("scrypt failed");
1267 return -1;
1268 }
1269 break;
1270
1271 case KDF_SCRYPT:
1272 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1273 SLOGE("scrypt failed");
1274 return -1;
1275 }
1276 break;
1277
1278 default:
1279 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001280 return -1;
1281 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001282
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001283 /* Initialize the decryption engine */
1284 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1285 SLOGE("EVP_EncryptInit failed\n");
1286 return -1;
1287 }
1288 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001289
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001290 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001291 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
1292 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001293 SLOGE("EVP_EncryptUpdate failed\n");
1294 return -1;
1295 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001296 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001297 SLOGE("EVP_EncryptFinal failed\n");
1298 return -1;
1299 }
1300
1301 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1302 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1303 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001304 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001305
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001306 /* Store the scrypt of the intermediate key, so we can validate if it's a
1307 password error or mount error when things go wrong.
1308 Note there's no need to check for errors, since if this is incorrect, we
1309 simply won't wipe userdata, which is the correct default behavior
1310 */
1311 int N = 1 << crypt_ftr->N_factor;
1312 int r = 1 << crypt_ftr->r_factor;
1313 int p = 1 << crypt_ftr->p_factor;
1314
1315 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1316 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1317 crypt_ftr->scrypted_intermediate_key,
1318 sizeof(crypt_ftr->scrypted_intermediate_key));
1319
1320 if (rc) {
1321 SLOGE("encrypt_master_key: crypto_scrypt failed");
1322 }
1323
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001324 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001325}
1326
JP Abgrall7bdfa522013-11-15 13:42:56 -08001327static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001328 unsigned char *encrypted_master_key,
1329 unsigned char *decrypted_master_key,
1330 kdf_func kdf, void *kdf_params,
1331 unsigned char** intermediate_key,
1332 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001333{
1334 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001335 EVP_CIPHER_CTX d_ctx;
1336 int decrypted_len, final_len;
1337
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001338 /* Turn the password into an intermediate key and IV that can decrypt the
1339 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001340 if (kdf(passwd, salt, ikey, kdf_params)) {
1341 SLOGE("kdf failed");
1342 return -1;
1343 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001344
1345 /* Initialize the decryption engine */
1346 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1347 return -1;
1348 }
1349 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1350 /* Decrypt the master key */
1351 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1352 encrypted_master_key, KEY_LEN_BYTES)) {
1353 return -1;
1354 }
1355 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1356 return -1;
1357 }
1358
1359 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1360 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001361 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001362
1363 /* Copy intermediate key if needed by params */
1364 if (intermediate_key && intermediate_key_size) {
1365 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1366 if (intermediate_key) {
1367 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1368 *intermediate_key_size = KEY_LEN_BYTES;
1369 }
1370 }
1371
1372 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001373}
1374
Kenny Rootc4c70f12013-06-14 12:11:38 -07001375static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001376{
Shawn Willdene17a9c42014-09-08 13:04:08 -06001377 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER_UNPADDED ||
1378 ftr->kdf_type == KDF_SCRYPT_KEYMASTER_BADLY_PADDED ||
1379 ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001380 *kdf = scrypt_keymaster;
1381 *kdf_params = ftr;
1382 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001383 *kdf = scrypt;
1384 *kdf_params = ftr;
1385 } else {
1386 *kdf = pbkdf2;
1387 *kdf_params = NULL;
1388 }
1389}
1390
JP Abgrall7bdfa522013-11-15 13:42:56 -08001391static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001392 struct crypt_mnt_ftr *crypt_ftr,
1393 unsigned char** intermediate_key,
1394 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001395{
1396 kdf_func kdf;
1397 void *kdf_params;
1398 int ret;
1399
1400 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001401 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1402 decrypted_master_key, kdf, kdf_params,
1403 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001404 if (ret != 0) {
1405 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001406 }
1407
1408 return ret;
1409}
1410
1411static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1412 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001413 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001414 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001415 EVP_CIPHER_CTX e_ctx;
1416 int encrypted_len, final_len;
1417
1418 /* Get some random bits for a key */
1419 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001420 read(fd, key_buf, sizeof(key_buf));
1421 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001422 close(fd);
1423
1424 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001425 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001426}
1427
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001428static int wait_and_unmount(char *mountpoint)
1429{
1430 int i, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001431#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001432
1433 /* Now umount the tmpfs filesystem */
1434 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
1435 if (umount(mountpoint)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001436 if (errno == EINVAL) {
1437 /* EINVAL is returned if the directory is not a mountpoint,
1438 * i.e. there is no filesystem mounted there. So just get out.
1439 */
1440 break;
1441 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001442 sleep(1);
1443 i++;
1444 } else {
1445 break;
1446 }
1447 }
1448
1449 if (i < WAIT_UNMOUNT_COUNT) {
1450 SLOGD("unmounting %s succeeded\n", mountpoint);
1451 rc = 0;
1452 } else {
1453 SLOGE("unmounting %s failed\n", mountpoint);
1454 rc = -1;
1455 }
1456
1457 return rc;
1458}
1459
Ken Sumrallc5872692013-05-14 15:26:31 -07001460#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001461static int prep_data_fs(void)
1462{
1463 int i;
1464
1465 /* Do the prep of the /data filesystem */
1466 property_set("vold.post_fs_data_done", "0");
1467 property_set("vold.decrypt", "trigger_post_fs_data");
1468 SLOGD("Just triggered post_fs_data\n");
1469
Ken Sumrallc5872692013-05-14 15:26:31 -07001470 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001471 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001472 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001473
1474 property_get("vold.post_fs_data_done", p, "0");
1475 if (*p == '1') {
1476 break;
1477 } else {
1478 usleep(250000);
1479 }
1480 }
1481 if (i == DATA_PREP_TIMEOUT) {
1482 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001483 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001484 return -1;
1485 } else {
1486 SLOGD("post_fs_data done\n");
1487 return 0;
1488 }
1489}
1490
Paul Lawrence74f29f12014-08-28 15:54:10 -07001491static void cryptfs_set_corrupt()
1492{
1493 // Mark the footer as bad
1494 struct crypt_mnt_ftr crypt_ftr;
1495 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1496 SLOGE("Failed to get crypto footer - panic");
1497 return;
1498 }
1499
1500 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1501 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1502 SLOGE("Failed to set crypto footer - panic");
1503 return;
1504 }
1505}
1506
1507static void cryptfs_trigger_restart_min_framework()
1508{
1509 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1510 SLOGE("Failed to mount tmpfs on data - panic");
1511 return;
1512 }
1513
1514 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1515 SLOGE("Failed to trigger post fs data - panic");
1516 return;
1517 }
1518
1519 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1520 SLOGE("Failed to trigger restart min framework - panic");
1521 return;
1522 }
1523}
1524
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001525/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001526static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001527{
1528 char fs_type[32];
1529 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001530 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001531 char fs_options[256];
1532 unsigned long mnt_flags;
1533 struct stat statbuf;
1534 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001535 static int restart_successful = 0;
1536
1537 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001538 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001539 SLOGE("Encrypted filesystem not validated, aborting");
1540 return -1;
1541 }
1542
1543 if (restart_successful) {
1544 SLOGE("System already restarted with encrypted disk, aborting");
1545 return -1;
1546 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001547
Paul Lawrencef4faa572014-01-29 13:31:03 -08001548 if (restart_main) {
1549 /* Here is where we shut down the framework. The init scripts
1550 * start all services in one of three classes: core, main or late_start.
1551 * On boot, we start core and main. Now, we stop main, but not core,
1552 * as core includes vold and a few other really important things that
1553 * we need to keep running. Once main has stopped, we should be able
1554 * to umount the tmpfs /data, then mount the encrypted /data.
1555 * We then restart the class main, and also the class late_start.
1556 * At the moment, I've only put a few things in late_start that I know
1557 * are not needed to bring up the framework, and that also cause problems
1558 * with unmounting the tmpfs /data, but I hope to add add more services
1559 * to the late_start class as we optimize this to decrease the delay
1560 * till the user is asked for the password to the filesystem.
1561 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001562
Paul Lawrencef4faa572014-01-29 13:31:03 -08001563 /* The init files are setup to stop the class main when vold.decrypt is
1564 * set to trigger_reset_main.
1565 */
1566 property_set("vold.decrypt", "trigger_reset_main");
1567 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001568
Paul Lawrencef4faa572014-01-29 13:31:03 -08001569 /* Ugh, shutting down the framework is not synchronous, so until it
1570 * can be fixed, this horrible hack will wait a moment for it all to
1571 * shut down before proceeding. Without it, some devices cannot
1572 * restart the graphics services.
1573 */
1574 sleep(2);
1575 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001576
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001577 /* Now that the framework is shutdown, we should be able to umount()
1578 * the tmpfs filesystem, and mount the real one.
1579 */
1580
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001581 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1582 if (strlen(crypto_blkdev) == 0) {
1583 SLOGE("fs_crypto_blkdev not set\n");
1584 return -1;
1585 }
1586
Ken Sumralle5032c42012-04-01 23:58:44 -07001587 if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001588 /* If ro.crypto.readonly is set to 1, mount the decrypted
1589 * filesystem readonly. This is used when /data is mounted by
1590 * recovery mode.
1591 */
1592 char ro_prop[PROPERTY_VALUE_MAX];
1593 property_get("ro.crypto.readonly", ro_prop, "");
1594 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1595 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1596 rec->flags |= MS_RDONLY;
1597 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001598
Ken Sumralle5032c42012-04-01 23:58:44 -07001599 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001600 int retries = RETRY_MOUNT_ATTEMPTS;
1601 int mount_rc;
1602 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1603 crypto_blkdev, 0))
1604 != 0) {
1605 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1606 /* TODO: invoke something similar to
1607 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1608 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1609 SLOGI("Failed to mount %s because it is busy - waiting",
1610 crypto_blkdev);
1611 if (--retries) {
1612 sleep(RETRY_MOUNT_DELAY_SECONDS);
1613 } else {
1614 /* Let's hope that a reboot clears away whatever is keeping
1615 the mount busy */
1616 cryptfs_reboot(reboot);
1617 }
1618 } else {
1619 SLOGE("Failed to mount decrypted data");
1620 cryptfs_set_corrupt();
1621 cryptfs_trigger_restart_min_framework();
1622 SLOGI("Started framework to offer wipe");
1623 return -1;
1624 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001625 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001626
Ken Sumralle5032c42012-04-01 23:58:44 -07001627 property_set("vold.decrypt", "trigger_load_persist_props");
1628 /* Create necessary paths on /data */
1629 if (prep_data_fs()) {
1630 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001631 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001632
1633 /* startup service classes main and late_start */
1634 property_set("vold.decrypt", "trigger_restart_framework");
1635 SLOGD("Just triggered restart_framework\n");
1636
1637 /* Give it a few moments to get started */
1638 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001639 }
1640
Ken Sumrall0cc16632011-01-18 20:32:26 -08001641 if (rc == 0) {
1642 restart_successful = 1;
1643 }
1644
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001645 return rc;
1646}
1647
Paul Lawrencef4faa572014-01-29 13:31:03 -08001648int cryptfs_restart(void)
1649{
1650 /* Call internal implementation forcing a restart of main service group */
1651 return cryptfs_restart_internal(1);
1652}
1653
Mark Salyzyn3e971272014-01-21 13:27:04 -08001654static int do_crypto_complete(char *mount_point UNUSED)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001655{
1656 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001657 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001658 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001659
1660 property_get("ro.crypto.state", encrypted_state, "");
1661 if (strcmp(encrypted_state, "encrypted") ) {
1662 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001663 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001664 }
1665
Ken Sumrall160b4d62013-04-22 12:15:39 -07001666 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001667 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001668
Ken Sumralle1a45852011-12-14 21:24:27 -08001669 /*
1670 * Only report this error if key_loc is a file and it exists.
1671 * If the device was never encrypted, and /data is not mountable for
1672 * some reason, returning 1 should prevent the UI from presenting the
1673 * a "enter password" screen, or worse, a "press button to wipe the
1674 * device" screen.
1675 */
1676 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1677 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001678 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001679 } else {
1680 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001681 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001682 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001683 }
1684
Paul Lawrence74f29f12014-08-28 15:54:10 -07001685 // Test for possible error flags
1686 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1687 SLOGE("Encryption process is partway completed\n");
1688 return CRYPTO_COMPLETE_PARTIAL;
1689 }
1690
1691 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1692 SLOGE("Encryption process was interrupted but cannot continue\n");
1693 return CRYPTO_COMPLETE_INCONSISTENT;
1694 }
1695
1696 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1697 SLOGE("Encryption is successful but data is corrupt\n");
1698 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001699 }
1700
1701 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001702 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001703}
1704
Paul Lawrencef4faa572014-01-29 13:31:03 -08001705static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1706 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001707{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001708 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001709 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001710 char crypto_blkdev[MAXPATHLEN];
1711 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001712 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001713 unsigned int orig_failed_decrypt_count;
1714 int rc;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001715 kdf_func kdf;
1716 void *kdf_params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001717 int use_keymaster = 0;
1718 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001719 unsigned char* intermediate_key = 0;
1720 size_t intermediate_key_size = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001721
Paul Lawrencef4faa572014-01-29 13:31:03 -08001722 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1723 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001724
Paul Lawrencef4faa572014-01-29 13:31:03 -08001725 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001726 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1727 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001728 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001729 rc = -1;
1730 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001731 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001732 }
1733
Paul Lawrencef4faa572014-01-29 13:31:03 -08001734 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1735
Paul Lawrence74f29f12014-08-28 15:54:10 -07001736 // Create crypto block device - all (non fatal) code paths
1737 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001738 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1739 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001740 SLOGE("Error creating decrypted block device\n");
1741 rc = -1;
1742 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001743 }
1744
Paul Lawrence74f29f12014-08-28 15:54:10 -07001745 /* Work out if the problem is the password or the data */
1746 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1747 scrypted_intermediate_key)];
1748 int N = 1 << crypt_ftr->N_factor;
1749 int r = 1 << crypt_ftr->r_factor;
1750 int p = 1 << crypt_ftr->p_factor;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001751
Paul Lawrence74f29f12014-08-28 15:54:10 -07001752 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1753 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1754 N, r, p, scrypted_intermediate_key,
1755 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001756
Paul Lawrence74f29f12014-08-28 15:54:10 -07001757 // Does the key match the crypto footer?
1758 if (rc == 0 && memcmp(scrypted_intermediate_key,
1759 crypt_ftr->scrypted_intermediate_key,
1760 sizeof(scrypted_intermediate_key)) == 0) {
1761 SLOGI("Password matches");
1762 rc = 0;
1763 } else {
1764 /* Try mounting the file system anyway, just in case the problem's with
1765 * the footer, not the key. */
1766 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1767 mkdir(tmp_mount_point, 0755);
1768 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1769 SLOGE("Error temp mounting decrypted block device\n");
1770 delete_crypto_blk_dev(label);
1771
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001772 rc = ++crypt_ftr->failed_decrypt_count;
1773 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001774 } else {
1775 /* Success! */
1776 SLOGI("Password did not match but decrypted drive mounted - continue");
1777 umount(tmp_mount_point);
1778 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001779 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001780 }
1781
1782 if (rc == 0) {
1783 crypt_ftr->failed_decrypt_count = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001784
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001785 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001786 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001787 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001788
1789 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001790 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001791 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001792 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001793 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001794 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001795 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001796
Paul Lawrence74f29f12014-08-28 15:54:10 -07001797 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001798 use_keymaster = keymaster_check_compatibility();
1799 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001800 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001801 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1802 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1803 upgrade = 1;
1804 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001805 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001806 upgrade = 1;
1807 }
1808
1809 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001810 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1811 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001812 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001813 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001814 }
1815 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001816
1817 // Do not fail even if upgrade failed - machine is bootable
1818 // Note that if this code is ever hit, there is a *serious* problem
1819 // since KDFs should never fail. You *must* fix the kdf before
1820 // proceeding!
1821 if (rc) {
1822 SLOGW("Upgrade failed with error %d,"
1823 " but continuing with previous state",
1824 rc);
1825 rc = 0;
1826 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001827 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001828 }
1829
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001830 errout:
1831 if (intermediate_key) {
1832 memset(intermediate_key, 0, intermediate_key_size);
1833 free(intermediate_key);
1834 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001835 return rc;
1836}
1837
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001838/* Called by vold when it wants to undo the crypto mapping of a volume it
1839 * manages. This is usually in response to a factory reset, when we want
1840 * to undo the crypto mapping so the volume is formatted in the clear.
1841 */
1842int cryptfs_revert_volume(const char *label)
1843{
1844 return delete_crypto_blk_dev((char *)label);
1845}
1846
Ken Sumrall29d8da82011-05-18 17:20:07 -07001847/*
1848 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1849 * Setup a dm-crypt mapping, use the saved master key from
1850 * setting up the /data mapping, and return the new device path.
1851 */
1852int cryptfs_setup_volume(const char *label, int major, int minor,
1853 char *crypto_sys_path, unsigned int max_path,
1854 int *new_major, int *new_minor)
1855{
1856 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1857 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001858 struct stat statbuf;
1859 int nr_sec, fd;
1860
1861 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1862
Ken Sumrall160b4d62013-04-22 12:15:39 -07001863 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001864
1865 /* Update the fs_size field to be the size of the volume */
1866 fd = open(real_blkdev, O_RDONLY);
1867 nr_sec = get_blkdev_size(fd);
1868 close(fd);
1869 if (nr_sec == 0) {
1870 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1871 return -1;
1872 }
1873
1874 sd_crypt_ftr.fs_size = nr_sec;
1875 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1876 crypto_blkdev, label);
1877
1878 stat(crypto_blkdev, &statbuf);
1879 *new_major = MAJOR(statbuf.st_rdev);
1880 *new_minor = MINOR(statbuf.st_rdev);
1881
1882 /* Create path to sys entry for this block device */
1883 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1884
1885 return 0;
1886}
1887
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001888int cryptfs_crypto_complete(void)
1889{
1890 return do_crypto_complete("/data");
1891}
1892
Paul Lawrencef4faa572014-01-29 13:31:03 -08001893int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1894{
1895 char encrypted_state[PROPERTY_VALUE_MAX];
1896 property_get("ro.crypto.state", encrypted_state, "");
1897 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1898 SLOGE("encrypted fs already validated or not running with encryption,"
1899 " aborting");
1900 return -1;
1901 }
1902
1903 if (get_crypt_ftr_and_key(crypt_ftr)) {
1904 SLOGE("Error getting crypt footer and key");
1905 return -1;
1906 }
1907
1908 return 0;
1909}
1910
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001911int cryptfs_check_passwd(char *passwd)
1912{
Paul Lawrencef4faa572014-01-29 13:31:03 -08001913 struct crypt_mnt_ftr crypt_ftr;
1914 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001915
Paul Lawrencef4faa572014-01-29 13:31:03 -08001916 rc = check_unmounted_and_get_ftr(&crypt_ftr);
1917 if (rc)
1918 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001919
Paul Lawrencef4faa572014-01-29 13:31:03 -08001920 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
1921 DATA_MNT_POINT, "userdata");
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001922
1923 if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001924 cryptfs_clear_password();
1925 password = strdup(passwd);
1926 struct timespec now;
1927 clock_gettime(CLOCK_BOOTTIME, &now);
1928 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001929 }
1930
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001931 return rc;
1932}
1933
Ken Sumrall3ad90722011-10-04 20:38:29 -07001934int cryptfs_verify_passwd(char *passwd)
1935{
1936 struct crypt_mnt_ftr crypt_ftr;
1937 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001938 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001939 char encrypted_state[PROPERTY_VALUE_MAX];
1940 int rc;
1941
1942 property_get("ro.crypto.state", encrypted_state, "");
1943 if (strcmp(encrypted_state, "encrypted") ) {
1944 SLOGE("device not encrypted, aborting");
1945 return -2;
1946 }
1947
1948 if (!master_key_saved) {
1949 SLOGE("encrypted fs not yet mounted, aborting");
1950 return -1;
1951 }
1952
1953 if (!saved_mount_point) {
1954 SLOGE("encrypted fs failed to save mount point, aborting");
1955 return -1;
1956 }
1957
Ken Sumrall160b4d62013-04-22 12:15:39 -07001958 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001959 SLOGE("Error getting crypt footer and key\n");
1960 return -1;
1961 }
1962
1963 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1964 /* If the device has no password, then just say the password is valid */
1965 rc = 0;
1966 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001967 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001968 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1969 /* They match, the password is correct */
1970 rc = 0;
1971 } else {
1972 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1973 sleep(1);
1974 rc = 1;
1975 }
1976 }
1977
1978 return rc;
1979}
1980
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001981/* Initialize a crypt_mnt_ftr structure. The keysize is
1982 * defaulted to 16 bytes, and the filesystem size to 0.
1983 * Presumably, at a minimum, the caller will update the
1984 * filesystem size and crypto_type_name after calling this function.
1985 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001986static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001987{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001988 off64_t off;
1989
1990 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001991 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001992 ftr->major_version = CURRENT_MAJOR_VERSION;
1993 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001994 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001995 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001996
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001997 switch (keymaster_check_compatibility()) {
1998 case 1:
1999 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2000 break;
2001
2002 case 0:
2003 ftr->kdf_type = KDF_SCRYPT;
2004 break;
2005
2006 default:
2007 SLOGE("keymaster_check_compatibility failed");
2008 return -1;
2009 }
2010
Kenny Rootc4c70f12013-06-14 12:11:38 -07002011 get_device_scrypt_params(ftr);
2012
Ken Sumrall160b4d62013-04-22 12:15:39 -07002013 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2014 if (get_crypt_ftr_info(NULL, &off) == 0) {
2015 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
2016 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
2017 ftr->persist_data_size;
2018 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002019
2020 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002021}
2022
Ken Sumrall29d8da82011-05-18 17:20:07 -07002023static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002024{
Ken Sumralle550f782013-08-20 13:48:23 -07002025 const char *args[10];
2026 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
2027 int num_args;
2028 int status;
2029 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002030 int rc = -1;
2031
Ken Sumrall29d8da82011-05-18 17:20:07 -07002032 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07002033 args[0] = "/system/bin/make_ext4fs";
2034 args[1] = "-a";
2035 args[2] = "/data";
2036 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07002037 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07002038 args[4] = size_str;
2039 args[5] = crypto_blkdev;
2040 num_args = 6;
2041 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
2042 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07002043 } else if (type == F2FS_FS) {
2044 args[0] = "/system/bin/mkfs.f2fs";
2045 args[1] = "-t";
2046 args[2] = "-d1";
2047 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07002048 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07002049 args[4] = size_str;
2050 num_args = 5;
2051 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
2052 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002053 } else {
2054 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
2055 return -1;
2056 }
2057
Ken Sumralle550f782013-08-20 13:48:23 -07002058 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
2059
2060 if (tmp != 0) {
2061 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002062 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07002063 if (WIFEXITED(status)) {
2064 if (WEXITSTATUS(status)) {
2065 SLOGE("Error creating filesystem on %s, exit status %d ",
2066 crypto_blkdev, WEXITSTATUS(status));
2067 } else {
2068 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
2069 rc = 0;
2070 }
2071 } else {
2072 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
2073 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002074 }
2075
2076 return rc;
2077}
2078
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002079#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08002080#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
2081#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002082
2083/* aligned 32K writes tends to make flash happy.
2084 * SD card association recommends it.
2085 */
2086#define BLOCKS_AT_A_TIME 8
2087
2088struct encryptGroupsData
2089{
2090 int realfd;
2091 int cryptofd;
2092 off64_t numblocks;
2093 off64_t one_pct, cur_pct, new_pct;
2094 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002095 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002096 char* real_blkdev, * crypto_blkdev;
2097 int count;
2098 off64_t offset;
2099 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08002100 off64_t last_written_sector;
2101 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002102 time_t time_started;
2103 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002104};
2105
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002106static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002107{
2108 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002109
2110 if (is_used) {
2111 data->used_blocks_already_done++;
2112 }
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002113 if (data->tot_used_blocks) {
2114 data->new_pct = data->used_blocks_already_done / data->one_pct;
2115 } else {
2116 data->new_pct = data->blocks_already_done / data->one_pct;
2117 }
2118
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002119 if (data->new_pct > data->cur_pct) {
2120 char buf[8];
2121 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07002122 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002123 property_set("vold.encrypt_progress", buf);
2124 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002125
2126 if (data->cur_pct >= 5) {
2127 double elapsed_time = difftime(time(NULL), data->time_started);
2128 off64_t remaining_blocks = data->tot_used_blocks
2129 - data->used_blocks_already_done;
2130 int remaining_time = (int)(elapsed_time * remaining_blocks
2131 / data->used_blocks_already_done);
Paul Lawrence71577502014-08-13 14:55:55 -07002132
2133 // Change time only if not yet set, lower, or a lot higher for
2134 // best user experience
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002135 if (data->remaining_time == -1
Paul Lawrence71577502014-08-13 14:55:55 -07002136 || remaining_time < data->remaining_time
2137 || remaining_time > data->remaining_time + 60) {
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002138 char buf[8];
2139 snprintf(buf, sizeof(buf), "%d", remaining_time);
2140 property_set("vold.encrypt_time_remaining", buf);
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002141 data->remaining_time = remaining_time;
2142 }
2143 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002144}
2145
Paul Lawrence3846be12014-09-22 11:33:54 -07002146static void log_progress(struct encryptGroupsData const* data, bool completed)
2147{
2148 // Precondition - if completed data = 0 else data != 0
2149
2150 // Track progress so we can skip logging blocks
2151 static off64_t offset = -1;
2152
2153 // Need to close existing 'Encrypting from' log?
2154 if (completed || (offset != -1 && data->offset != offset)) {
2155 SLOGI("Encrypted to sector %" PRId64,
2156 offset / info.block_size * CRYPT_SECTOR_SIZE);
2157 offset = -1;
2158 }
2159
2160 // Need to start new 'Encrypting from' log?
2161 if (!completed && offset != data->offset) {
2162 SLOGI("Encrypting from sector %" PRId64,
2163 data->offset / info.block_size * CRYPT_SECTOR_SIZE);
2164 }
2165
2166 // Update offset
2167 if (!completed) {
2168 offset = data->offset + (off64_t)data->count * info.block_size;
2169 }
2170}
2171
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002172static int flush_outstanding_data(struct encryptGroupsData* data)
2173{
2174 if (data->count == 0) {
2175 return 0;
2176 }
2177
Elliott Hughes231bdba2014-06-25 18:36:19 -07002178 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002179
2180 if (pread64(data->realfd, data->buffer,
2181 info.block_size * data->count, data->offset)
2182 <= 0) {
2183 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2184 data->real_blkdev);
2185 return -1;
2186 }
2187
2188 if (pwrite64(data->cryptofd, data->buffer,
2189 info.block_size * data->count, data->offset)
2190 <= 0) {
2191 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2192 data->crypto_blkdev);
2193 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002194 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002195 log_progress(data, false);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002196 }
2197
2198 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002199 data->last_written_sector = (data->offset + data->count)
2200 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002201 return 0;
2202}
2203
2204static int encrypt_groups(struct encryptGroupsData* data)
2205{
2206 unsigned int i;
2207 u8 *block_bitmap = 0;
2208 unsigned int block;
2209 off64_t ret;
2210 int rc = -1;
2211
2212 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
2213 if (!data->buffer) {
2214 SLOGE("Failed to allocate crypto buffer");
2215 goto errout;
2216 }
2217
2218 block_bitmap = malloc(info.block_size);
2219 if (!block_bitmap) {
2220 SLOGE("failed to allocate block bitmap");
2221 goto errout;
2222 }
2223
2224 for (i = 0; i < aux_info.groups; ++i) {
2225 SLOGI("Encrypting group %d", i);
2226
2227 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2228 u32 block_count = min(info.blocks_per_group,
2229 aux_info.len_blocks - first_block);
2230
2231 off64_t offset = (u64)info.block_size
2232 * aux_info.bg_desc[i].bg_block_bitmap;
2233
2234 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2235 if (ret != (int)info.block_size) {
2236 SLOGE("failed to read all of block group bitmap %d", i);
2237 goto errout;
2238 }
2239
2240 offset = (u64)info.block_size * first_block;
2241
2242 data->count = 0;
2243
2244 for (block = 0; block < block_count; block++) {
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002245 int used = bitmap_get_bit(block_bitmap, block);
2246 update_progress(data, used);
2247 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002248 if (data->count == 0) {
2249 data->offset = offset;
2250 }
2251 data->count++;
2252 } else {
2253 if (flush_outstanding_data(data)) {
2254 goto errout;
2255 }
2256 }
2257
2258 offset += info.block_size;
2259
2260 /* Write data if we are aligned or buffer size reached */
2261 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2262 || data->count == BLOCKS_AT_A_TIME) {
2263 if (flush_outstanding_data(data)) {
2264 goto errout;
2265 }
2266 }
Paul Lawrence87999172014-02-20 12:21:31 -08002267
Paul Lawrence73d7a022014-06-09 14:10:09 -07002268 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002269 SLOGE("Stopping encryption due to low battery");
2270 rc = 0;
2271 goto errout;
2272 }
2273
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002274 }
2275 if (flush_outstanding_data(data)) {
2276 goto errout;
2277 }
2278 }
2279
Paul Lawrence87999172014-02-20 12:21:31 -08002280 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002281 rc = 0;
2282
2283errout:
Paul Lawrence3846be12014-09-22 11:33:54 -07002284 log_progress(0, true);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002285 free(data->buffer);
2286 free(block_bitmap);
2287 return rc;
2288}
2289
2290static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2291 char *real_blkdev,
2292 off64_t size,
2293 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002294 off64_t tot_size,
2295 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002296{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002297 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002298 struct encryptGroupsData data;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002299 int rc; // Can't initialize without causing warning -Wclobbered
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002300
Paul Lawrence87999172014-02-20 12:21:31 -08002301 if (previously_encrypted_upto > *size_already_done) {
2302 SLOGD("Not fast encrypting since resuming part way through");
2303 return -1;
2304 }
2305
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002306 memset(&data, 0, sizeof(data));
2307 data.real_blkdev = real_blkdev;
2308 data.crypto_blkdev = crypto_blkdev;
2309
2310 if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
2311 SLOGE("Error opening real_blkdev %s for inplace encrypt\n",
2312 real_blkdev);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002313 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002314 goto errout;
2315 }
2316
2317 if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
2318 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n",
2319 crypto_blkdev);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002320 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002321 goto errout;
2322 }
2323
2324 if (setjmp(setjmp_env)) {
2325 SLOGE("Reading extent caused an exception");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002326 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002327 goto errout;
2328 }
2329
2330 if (read_ext(data.realfd, 0) != 0) {
2331 SLOGE("Failed to read extent");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002332 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002333 goto errout;
2334 }
2335
2336 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2337 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2338 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2339
2340 SLOGI("Encrypting filesystem in place...");
2341
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002342 data.tot_used_blocks = data.numblocks;
2343 for (i = 0; i < aux_info.groups; ++i) {
2344 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2345 }
2346
2347 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002348 data.cur_pct = 0;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002349 data.time_started = time(NULL);
2350 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002351
2352 rc = encrypt_groups(&data);
2353 if (rc) {
2354 SLOGE("Error encrypting groups");
2355 goto errout;
2356 }
2357
Paul Lawrence87999172014-02-20 12:21:31 -08002358 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002359 rc = 0;
2360
2361errout:
2362 close(data.realfd);
2363 close(data.cryptofd);
2364
2365 return rc;
2366}
2367
Paul Lawrence3846be12014-09-22 11:33:54 -07002368static void log_progress_f2fs(u64 block, bool completed)
2369{
2370 // Precondition - if completed data = 0 else data != 0
2371
2372 // Track progress so we can skip logging blocks
2373 static u64 last_block = (u64)-1;
2374
2375 // Need to close existing 'Encrypting from' log?
2376 if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
2377 SLOGI("Encrypted to block %" PRId64, last_block);
2378 last_block = -1;
2379 }
2380
2381 // Need to start new 'Encrypting from' log?
2382 if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
2383 SLOGI("Encrypting from block %" PRId64, block);
2384 }
2385
2386 // Update offset
2387 if (!completed) {
2388 last_block = block;
2389 }
2390}
2391
Daniel Rosenberge82df162014-08-15 22:19:23 +00002392static int encrypt_one_block_f2fs(u64 pos, void *data)
2393{
2394 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2395
2396 priv_dat->blocks_already_done = pos - 1;
2397 update_progress(priv_dat, 1);
2398
2399 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2400
2401 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
2402 SLOGE("Error reading real_blkdev %s for inplace encrypt", priv_dat->crypto_blkdev);
2403 return -1;
2404 }
2405
2406 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
2407 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", priv_dat->crypto_blkdev);
2408 return -1;
2409 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002410 log_progress_f2fs(pos, false);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002411 }
2412
2413 return 0;
2414}
2415
2416static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2417 char *real_blkdev,
2418 off64_t size,
2419 off64_t *size_already_done,
2420 off64_t tot_size,
2421 off64_t previously_encrypted_upto)
2422{
2423 u32 i;
2424 struct encryptGroupsData data;
2425 struct f2fs_info *f2fs_info = NULL;
2426 int rc = -1;
2427 if (previously_encrypted_upto > *size_already_done) {
2428 SLOGD("Not fast encrypting since resuming part way through");
2429 return -1;
2430 }
2431 memset(&data, 0, sizeof(data));
2432 data.real_blkdev = real_blkdev;
2433 data.crypto_blkdev = crypto_blkdev;
2434 data.realfd = -1;
2435 data.cryptofd = -1;
2436 if ( (data.realfd = open64(real_blkdev, O_RDWR)) < 0) {
2437 SLOGE("Error opening real_blkdev %s for inplace encrypt\n",
2438 real_blkdev);
2439 goto errout;
2440 }
2441 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY)) < 0) {
2442 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n",
2443 crypto_blkdev);
2444 goto errout;
2445 }
2446
2447 f2fs_info = generate_f2fs_info(data.realfd);
2448 if (!f2fs_info)
2449 goto errout;
2450
2451 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2452 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2453 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2454
2455 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2456
2457 data.one_pct = data.tot_used_blocks / 100;
2458 data.cur_pct = 0;
2459 data.time_started = time(NULL);
2460 data.remaining_time = -1;
2461
2462 data.buffer = malloc(f2fs_info->block_size);
2463 if (!data.buffer) {
2464 SLOGE("Failed to allocate crypto buffer");
2465 goto errout;
2466 }
2467
2468 data.count = 0;
2469
2470 /* Currently, this either runs to completion, or hits a nonrecoverable error */
2471 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2472
2473 if (rc) {
2474 SLOGE("Error in running over blocks");
2475 goto errout;
2476 }
2477
2478 *size_already_done += size;
2479 rc = 0;
2480
2481errout:
2482 if (rc)
2483 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2484
Paul Lawrence3846be12014-09-22 11:33:54 -07002485 log_progress_f2fs(0, true);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002486 free(f2fs_info);
2487 free(data.buffer);
2488 close(data.realfd);
2489 close(data.cryptofd);
2490
2491 return rc;
2492}
2493
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002494static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2495 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002496 off64_t tot_size,
2497 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002498{
2499 int realfd, cryptofd;
2500 char *buf[CRYPT_INPLACE_BUFSIZE];
2501 int rc = -1;
2502 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002503 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002504 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002505
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002506 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
2507 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
2508 return -1;
2509 }
2510
2511 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
2512 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
2513 close(realfd);
2514 return -1;
2515 }
2516
2517 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2518 * The size passed in is the number of 512 byte sectors in the filesystem.
2519 * So compute the number of whole 4K blocks we should read/write,
2520 * and the remainder.
2521 */
2522 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2523 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002524 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2525 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002526
2527 SLOGE("Encrypting filesystem in place...");
2528
Paul Lawrence87999172014-02-20 12:21:31 -08002529 i = previously_encrypted_upto + 1 - *size_already_done;
2530
2531 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2532 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2533 goto errout;
2534 }
2535
2536 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2537 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2538 goto errout;
2539 }
2540
2541 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2542 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2543 SLOGE("Error reading initial sectors from real_blkdev %s for "
2544 "inplace encrypt\n", crypto_blkdev);
2545 goto errout;
2546 }
2547 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2548 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2549 "inplace encrypt\n", crypto_blkdev);
2550 goto errout;
2551 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002552 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002553 }
2554 }
2555
Ken Sumrall29d8da82011-05-18 17:20:07 -07002556 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002557 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002558 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002559 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002560 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002561 if (new_pct > cur_pct) {
2562 char buf[8];
2563
2564 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002565 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002566 property_set("vold.encrypt_progress", buf);
2567 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002568 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002569 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002570 goto errout;
2571 }
2572 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002573 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2574 goto errout;
2575 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002576 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002577 CRYPT_SECTORS_PER_BUFSIZE,
2578 i * CRYPT_SECTORS_PER_BUFSIZE);
2579 }
2580
Paul Lawrence73d7a022014-06-09 14:10:09 -07002581 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002582 SLOGE("Stopping encryption due to low battery");
2583 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2584 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002585 goto errout;
2586 }
2587 }
2588
2589 /* Do any remaining sectors */
2590 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002591 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2592 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002593 goto errout;
2594 }
Paul Lawrence87999172014-02-20 12:21:31 -08002595 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2596 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002597 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002598 } else {
2599 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002600 }
2601 }
2602
Ken Sumrall29d8da82011-05-18 17:20:07 -07002603 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002604 rc = 0;
2605
2606errout:
2607 close(realfd);
2608 close(cryptofd);
2609
2610 return rc;
2611}
2612
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002613static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2614 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002615 off64_t tot_size,
2616 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002617{
Paul Lawrence87999172014-02-20 12:21:31 -08002618 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002619 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002620 }
2621
2622 if (*size_already_done + size < previously_encrypted_upto) {
2623 *size_already_done += size;
2624 return 0;
2625 }
2626
Daniel Rosenberge82df162014-08-15 22:19:23 +00002627 /* TODO: identify filesystem type.
2628 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2629 * then we will drop down to cryptfs_enable_inplace_f2fs.
2630 * */
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002631 if (cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002632 size, size_already_done,
2633 tot_size, previously_encrypted_upto) == 0) {
2634 return 0;
2635 }
2636
2637 if (cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
2638 size, size_already_done,
2639 tot_size, previously_encrypted_upto) == 0) {
2640 return 0;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002641 }
2642
2643 return cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002644 size, size_already_done, tot_size,
2645 previously_encrypted_upto);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002646}
2647
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002648#define CRYPTO_ENABLE_WIPE 1
2649#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002650
2651#define FRAMEWORK_BOOT_WAIT 60
2652
Ken Sumrall29d8da82011-05-18 17:20:07 -07002653static inline int should_encrypt(struct volume_info *volume)
2654{
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002655 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
Ken Sumrall29d8da82011-05-18 17:20:07 -07002656 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
2657}
2658
Paul Lawrence87999172014-02-20 12:21:31 -08002659static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2660{
2661 int fd = open(filename, O_RDONLY);
2662 if (fd == -1) {
2663 SLOGE("Error opening file %s", filename);
2664 return -1;
2665 }
2666
2667 char block[CRYPT_INPLACE_BUFSIZE];
2668 memset(block, 0, sizeof(block));
2669 if (unix_read(fd, block, sizeof(block)) < 0) {
2670 SLOGE("Error reading file %s", filename);
2671 close(fd);
2672 return -1;
2673 }
2674
2675 close(fd);
2676
2677 SHA256_CTX c;
2678 SHA256_Init(&c);
2679 SHA256_Update(&c, block, sizeof(block));
2680 SHA256_Final(buf, &c);
2681
2682 return 0;
2683}
2684
JP Abgrall62c7af32014-06-16 13:01:23 -07002685static int get_fs_type(struct fstab_rec *rec)
2686{
2687 if (!strcmp(rec->fs_type, "ext4")) {
2688 return EXT4_FS;
2689 } else if (!strcmp(rec->fs_type, "f2fs")) {
2690 return F2FS_FS;
2691 } else {
2692 return -1;
2693 }
2694}
2695
Paul Lawrence87999172014-02-20 12:21:31 -08002696static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2697 char *crypto_blkdev, char *real_blkdev,
2698 int previously_encrypted_upto)
2699{
2700 off64_t cur_encryption_done=0, tot_encryption_size=0;
2701 int i, rc = -1;
2702
Paul Lawrence73d7a022014-06-09 14:10:09 -07002703 if (!is_battery_ok_to_start()) {
2704 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002705 return 0;
2706 }
2707
2708 /* The size of the userdata partition, and add in the vold volumes below */
2709 tot_encryption_size = crypt_ftr->fs_size;
2710
2711 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002712 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2713 int fs_type = get_fs_type(rec);
2714 if (fs_type < 0) {
2715 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2716 return -1;
2717 }
2718 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002719 } else if (how == CRYPTO_ENABLE_INPLACE) {
2720 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2721 crypt_ftr->fs_size, &cur_encryption_done,
2722 tot_encryption_size,
2723 previously_encrypted_upto);
2724
Paul Lawrence73d7a022014-06-09 14:10:09 -07002725 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002726 crypt_ftr->encrypted_upto = cur_encryption_done;
2727 }
2728
Paul Lawrence73d7a022014-06-09 14:10:09 -07002729 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002730 /* The inplace routine never actually sets the progress to 100% due
2731 * to the round down nature of integer division, so set it here */
2732 property_set("vold.encrypt_progress", "100");
2733 }
2734 } else {
2735 /* Shouldn't happen */
2736 SLOGE("cryptfs_enable: internal error, unknown option\n");
2737 rc = -1;
2738 }
2739
2740 return rc;
2741}
2742
Paul Lawrence13486032014-02-03 13:28:11 -08002743int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
2744 int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002745{
2746 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002747 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07002748 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002749 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07002750 int rc=-1, fd, i, ret;
Paul Lawrence87999172014-02-20 12:21:31 -08002751 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002752 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002753 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002754 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002755 char key_loc[PROPERTY_VALUE_MAX];
2756 char fuse_sdcard[PROPERTY_VALUE_MAX];
2757 char *sd_mnt_point;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002758 int num_vols;
2759 struct volume_info *vol_list = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002760 off64_t previously_encrypted_upto = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002761
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002762 if (!strcmp(howarg, "wipe")) {
2763 how = CRYPTO_ENABLE_WIPE;
2764 } else if (! strcmp(howarg, "inplace")) {
2765 how = CRYPTO_ENABLE_INPLACE;
2766 } else {
2767 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002768 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002769 }
2770
Paul Lawrence87999172014-02-20 12:21:31 -08002771 /* See if an encryption was underway and interrupted */
2772 if (how == CRYPTO_ENABLE_INPLACE
2773 && get_crypt_ftr_and_key(&crypt_ftr) == 0
2774 && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
2775 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2776 crypt_ftr.encrypted_upto = 0;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002777 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
2778
2779 /* At this point, we are in an inconsistent state. Until we successfully
2780 complete encryption, a reboot will leave us broken. So mark the
2781 encryption failed in case that happens.
2782 On successfully completing encryption, remove this flag */
2783 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2784
2785 put_crypt_ftr_and_key(&crypt_ftr);
Paul Lawrence87999172014-02-20 12:21:31 -08002786 }
2787
2788 property_get("ro.crypto.state", encrypted_state, "");
2789 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2790 SLOGE("Device is already running encrypted, aborting");
2791 goto error_unencrypted;
2792 }
2793
2794 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2795 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002796 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002797
Ken Sumrall3ed82362011-01-28 23:31:16 -08002798 /* Get the size of the real block device */
2799 fd = open(real_blkdev, O_RDONLY);
2800 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
2801 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2802 goto error_unencrypted;
2803 }
2804 close(fd);
2805
2806 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002807 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002808 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002809 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002810 if (fs_size_sec == 0)
2811 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2812
Paul Lawrence87999172014-02-20 12:21:31 -08002813 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002814
2815 if (fs_size_sec > max_fs_size_sec) {
2816 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2817 goto error_unencrypted;
2818 }
2819 }
2820
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002821 /* Get a wakelock as this may take a while, and we don't want the
2822 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2823 * wants to keep the screen on, it can grab a full wakelock.
2824 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002825 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002826 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2827
Jeff Sharkey7382f812012-08-23 14:08:59 -07002828 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07002829 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07002830 if (!sd_mnt_point) {
2831 sd_mnt_point = getenv("EXTERNAL_STORAGE");
2832 }
2833 if (!sd_mnt_point) {
2834 sd_mnt_point = "/mnt/sdcard";
2835 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07002836
Paul Lawrence87999172014-02-20 12:21:31 -08002837 /* TODO
2838 * Currently do not have test devices with multiple encryptable volumes.
2839 * When we acquire some, re-add support.
2840 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002841 num_vols=vold_getNumDirectVolumes();
2842 vol_list = malloc(sizeof(struct volume_info) * num_vols);
2843 vold_getDirectVolumeList(vol_list);
2844
2845 for (i=0; i<num_vols; i++) {
2846 if (should_encrypt(&vol_list[i])) {
Paul Lawrence87999172014-02-20 12:21:31 -08002847 SLOGE("Cannot encrypt if there are multiple encryptable volumes"
2848 "%s\n", vol_list[i].label);
2849 goto error_unencrypted;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002850 }
2851 }
2852
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002853 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002854 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002855 */
2856 property_set("vold.decrypt", "trigger_shutdown_framework");
2857 SLOGD("Just asked init to shut down class main\n");
2858
Ken Sumrall425524d2012-06-14 20:55:28 -07002859 if (vold_unmountAllAsecs()) {
2860 /* Just report the error. If any are left mounted,
2861 * umounting /data below will fail and handle the error.
2862 */
2863 SLOGE("Error unmounting internal asecs");
2864 }
2865
Ken Sumrall29d8da82011-05-18 17:20:07 -07002866 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
2867 if (!strcmp(fuse_sdcard, "true")) {
2868 /* This is a device using the fuse layer to emulate the sdcard semantics
2869 * on top of the userdata partition. vold does not manage it, it is managed
2870 * by the sdcard service. The sdcard service was killed by the property trigger
2871 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
2872 * unlike the case for vold managed devices above.
2873 */
2874 if (wait_and_unmount(sd_mnt_point)) {
2875 goto error_shutting_down;
2876 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002877 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002878
2879 /* Now unmount the /data partition. */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002880 if (wait_and_unmount(DATA_MNT_POINT)) {
JP Abgrall502dc742013-11-01 13:06:20 -07002881 if (allow_reboot) {
2882 goto error_shutting_down;
2883 } else {
2884 goto error_unencrypted;
2885 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002886 }
2887
2888 /* Do extra work for a better UX when doing the long inplace encryption */
2889 if (how == CRYPTO_ENABLE_INPLACE) {
2890 /* Now that /data is unmounted, we need to mount a tmpfs
2891 * /data, set a property saying we're doing inplace encryption,
2892 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002893 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002894 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002895 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002896 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002897 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002898 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002899
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002900 /* restart the framework. */
2901 /* Create necessary paths on /data */
2902 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002903 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002904 }
2905
Ken Sumrall92736ef2012-10-17 20:57:14 -07002906 /* Ugh, shutting down the framework is not synchronous, so until it
2907 * can be fixed, this horrible hack will wait a moment for it all to
2908 * shut down before proceeding. Without it, some devices cannot
2909 * restart the graphics services.
2910 */
2911 sleep(2);
2912
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002913 /* startup service classes main and late_start */
2914 property_set("vold.decrypt", "trigger_restart_min_framework");
2915 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002916
Ken Sumrall7df84122011-01-18 14:04:08 -08002917 /* OK, the framework is restarted and will soon be showing a
2918 * progress bar. Time to setup an encrypted mapping, and
2919 * either write a new filesystem, or encrypt in place updating
2920 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002921 */
2922 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002923
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002924 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002925 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence87999172014-02-20 12:21:31 -08002926 if (previously_encrypted_upto == 0) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002927 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2928 goto error_shutting_down;
2929 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002930
Paul Lawrence87999172014-02-20 12:21:31 -08002931 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2932 crypt_ftr.fs_size = nr_sec
2933 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2934 } else {
2935 crypt_ftr.fs_size = nr_sec;
2936 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002937 /* At this point, we are in an inconsistent state. Until we successfully
2938 complete encryption, a reboot will leave us broken. So mark the
2939 encryption failed in case that happens.
2940 On successfully completing encryption, remove this flag */
2941 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence87999172014-02-20 12:21:31 -08002942 crypt_ftr.crypt_type = crypt_type;
2943 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002944
Paul Lawrence87999172014-02-20 12:21:31 -08002945 /* Make an encrypted master key */
2946 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
2947 SLOGE("Cannot create encrypted master key\n");
2948 goto error_shutting_down;
2949 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002950
Paul Lawrence87999172014-02-20 12:21:31 -08002951 /* Write the key to the end of the partition */
2952 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002953
Paul Lawrence87999172014-02-20 12:21:31 -08002954 /* If any persistent data has been remembered, save it.
2955 * If none, create a valid empty table and save that.
2956 */
2957 if (!persist_data) {
2958 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
2959 if (pdata) {
2960 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2961 persist_data = pdata;
2962 }
2963 }
2964 if (persist_data) {
2965 save_persistent_data();
2966 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002967 }
2968
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002969 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002970 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
2971 "userdata");
2972
Paul Lawrence87999172014-02-20 12:21:31 -08002973 /* If we are continuing, check checksums match */
2974 rc = 0;
2975 if (previously_encrypted_upto) {
2976 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2977 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002978
Paul Lawrence87999172014-02-20 12:21:31 -08002979 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2980 sizeof(hash_first_block)) != 0) {
2981 SLOGE("Checksums do not match - trigger wipe");
2982 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002983 }
2984 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002985
Paul Lawrence87999172014-02-20 12:21:31 -08002986 if (!rc) {
2987 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
2988 crypto_blkdev, real_blkdev,
2989 previously_encrypted_upto);
2990 }
2991
2992 /* Calculate checksum if we are not finished */
Paul Lawrence73d7a022014-06-09 14:10:09 -07002993 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002994 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2995 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002996 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002997 SLOGE("Error calculating checksum for continuing encryption");
2998 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002999 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003000 }
3001
3002 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003003 delete_crypto_blk_dev("userdata");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003004
3005 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003006
3007 if (! rc) {
3008 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003009 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08003010
Paul Lawrence6bfed202014-07-28 12:47:22 -07003011 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003012 SLOGD("Encrypted up to sector %lld - will continue after reboot",
3013 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07003014 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08003015 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07003016
Paul Lawrence6bfed202014-07-28 12:47:22 -07003017 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08003018
Paul Lawrence73d7a022014-06-09 14:10:09 -07003019 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003020 char value[PROPERTY_VALUE_MAX];
3021 property_get("ro.crypto.state", value, "");
3022 if (!strcmp(value, "")) {
3023 /* default encryption - continue first boot sequence */
3024 property_set("ro.crypto.state", "encrypted");
3025 release_wake_lock(lockid);
3026 cryptfs_check_passwd(DEFAULT_PASSWORD);
3027 cryptfs_restart_internal(1);
3028 return 0;
3029 } else {
3030 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08003031 cryptfs_reboot(reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003032 }
Paul Lawrence87999172014-02-20 12:21:31 -08003033 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003034 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Paul Lawrence87999172014-02-20 12:21:31 -08003035 cryptfs_reboot(shutdown);
3036 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003037 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003038 char value[PROPERTY_VALUE_MAX];
3039
Ken Sumrall319369a2012-06-27 16:30:18 -07003040 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003041 if (!strcmp(value, "1")) {
3042 /* wipe data if encryption failed */
3043 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
3044 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07003045 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003046 if (fd >= 0) {
Jeff Sharkeydd1a8042014-09-24 11:46:51 -07003047 write(fd, "--wipe_data\n", strlen("--wipe_data\n") + 1);
3048 write(fd, "--reason=cryptfs_enable_internal\n", strlen("--reason=cryptfs_enable_internal\n") + 1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003049 close(fd);
3050 } else {
3051 SLOGE("could not open /cache/recovery/command\n");
3052 }
Paul Lawrence87999172014-02-20 12:21:31 -08003053 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003054 } else {
3055 /* set property to trigger dialog */
3056 property_set("vold.encrypt_progress", "error_partially_encrypted");
3057 release_wake_lock(lockid);
3058 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003059 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003060 }
3061
Ken Sumrall3ed82362011-01-28 23:31:16 -08003062 /* hrm, the encrypt step claims success, but the reboot failed.
3063 * This should not happen.
3064 * Set the property and return. Hope the framework can deal with it.
3065 */
3066 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003067 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003068 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08003069
3070error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07003071 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003072 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003073 if (lockid[0]) {
3074 release_wake_lock(lockid);
3075 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003076 return -1;
3077
3078error_shutting_down:
3079 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3080 * but the framework is stopped and not restarted to show the error, so it's up to
3081 * vold to restart the system.
3082 */
3083 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08003084 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003085
3086 /* shouldn't get here */
3087 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003088 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003089 if (lockid[0]) {
3090 release_wake_lock(lockid);
3091 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003092 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003093}
3094
Paul Lawrence45f10532014-04-04 18:11:56 +00003095int cryptfs_enable(char *howarg, int type, char *passwd, int allow_reboot)
Paul Lawrence13486032014-02-03 13:28:11 -08003096{
Paul Lawrence45f10532014-04-04 18:11:56 +00003097 return cryptfs_enable_internal(howarg, type, passwd, allow_reboot);
Paul Lawrence13486032014-02-03 13:28:11 -08003098}
3099
3100int cryptfs_enable_default(char *howarg, int allow_reboot)
3101{
3102 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
3103 DEFAULT_PASSWORD, allow_reboot);
3104}
3105
3106int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003107{
3108 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003109 unsigned char decrypted_master_key[KEY_LEN_BYTES];
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
3130 encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
3131 : newpw,
3132 crypt_ftr.salt,
3133 saved_master_key,
3134 crypt_ftr.master_key,
3135 &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003136
Jason parks70a4b3f2011-01-28 10:10:47 -06003137 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003138 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003139
3140 return 0;
3141}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003142
3143static int persist_get_key(char *fieldname, char *value)
3144{
3145 unsigned int i;
3146
3147 if (persist_data == NULL) {
3148 return -1;
3149 }
3150 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3151 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3152 /* We found it! */
3153 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3154 return 0;
3155 }
3156 }
3157
3158 return -1;
3159}
3160
3161static int persist_set_key(char *fieldname, char *value, int encrypted)
3162{
3163 unsigned int i;
3164 unsigned int num;
3165 struct crypt_mnt_ftr crypt_ftr;
3166 unsigned int max_persistent_entries;
3167 unsigned int dsize;
3168
3169 if (persist_data == NULL) {
3170 return -1;
3171 }
3172
3173 /* If encrypted, use the values from the crypt_ftr, otherwise
3174 * use the values for the current spec.
3175 */
3176 if (encrypted) {
3177 if(get_crypt_ftr_and_key(&crypt_ftr)) {
3178 return -1;
3179 }
3180 dsize = crypt_ftr.persist_data_size;
3181 } else {
3182 dsize = CRYPT_PERSIST_DATA_SIZE;
3183 }
3184 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3185 sizeof(struct crypt_persist_entry);
3186
3187 num = persist_data->persist_valid_entries;
3188
3189 for (i = 0; i < num; i++) {
3190 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3191 /* We found an existing entry, update it! */
3192 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3193 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3194 return 0;
3195 }
3196 }
3197
3198 /* We didn't find it, add it to the end, if there is room */
3199 if (persist_data->persist_valid_entries < max_persistent_entries) {
3200 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3201 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3202 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3203 persist_data->persist_valid_entries++;
3204 return 0;
3205 }
3206
3207 return -1;
3208}
3209
3210/* Return the value of the specified field. */
3211int cryptfs_getfield(char *fieldname, char *value, int len)
3212{
3213 char temp_value[PROPERTY_VALUE_MAX];
3214 char real_blkdev[MAXPATHLEN];
3215 /* 0 is success, 1 is not encrypted,
3216 * -1 is value not set, -2 is any other error
3217 */
3218 int rc = -2;
3219
3220 if (persist_data == NULL) {
3221 load_persistent_data();
3222 if (persist_data == NULL) {
3223 SLOGE("Getfield error, cannot load persistent data");
3224 goto out;
3225 }
3226 }
3227
3228 if (!persist_get_key(fieldname, temp_value)) {
3229 /* We found it, copy it to the caller's buffer and return */
3230 strlcpy(value, temp_value, len);
3231 rc = 0;
3232 } else {
3233 /* Sadness, it's not there. Return the error */
3234 rc = -1;
3235 }
3236
3237out:
3238 return rc;
3239}
3240
3241/* Set the value of the specified field. */
3242int cryptfs_setfield(char *fieldname, char *value)
3243{
3244 struct crypt_persist_data stored_pdata;
3245 struct crypt_persist_data *pdata_p;
3246 struct crypt_mnt_ftr crypt_ftr;
3247 char encrypted_state[PROPERTY_VALUE_MAX];
3248 /* 0 is success, -1 is an error */
3249 int rc = -1;
3250 int encrypted = 0;
3251
3252 if (persist_data == NULL) {
3253 load_persistent_data();
3254 if (persist_data == NULL) {
3255 SLOGE("Setfield error, cannot load persistent data");
3256 goto out;
3257 }
3258 }
3259
3260 property_get("ro.crypto.state", encrypted_state, "");
3261 if (!strcmp(encrypted_state, "encrypted") ) {
3262 encrypted = 1;
3263 }
3264
3265 if (persist_set_key(fieldname, value, encrypted)) {
3266 goto out;
3267 }
3268
3269 /* If we are running encrypted, save the persistent data now */
3270 if (encrypted) {
3271 if (save_persistent_data()) {
3272 SLOGE("Setfield error, cannot save persistent data");
3273 goto out;
3274 }
3275 }
3276
3277 rc = 0;
3278
3279out:
3280 return rc;
3281}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003282
3283/* Checks userdata. Attempt to mount the volume if default-
3284 * encrypted.
3285 * On success trigger next init phase and return 0.
3286 * Currently do not handle failure - see TODO below.
3287 */
3288int cryptfs_mount_default_encrypted(void)
3289{
3290 char decrypt_state[PROPERTY_VALUE_MAX];
3291 property_get("vold.decrypt", decrypt_state, "0");
3292 if (!strcmp(decrypt_state, "0")) {
3293 SLOGE("Not encrypted - should not call here");
3294 } else {
3295 int crypt_type = cryptfs_get_password_type();
3296 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3297 SLOGE("Bad crypt type - error");
3298 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3299 SLOGD("Password is not default - "
3300 "starting min framework to prompt");
3301 property_set("vold.decrypt", "trigger_restart_min_framework");
3302 return 0;
3303 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3304 SLOGD("Password is default - restarting filesystem");
3305 cryptfs_restart_internal(0);
3306 return 0;
3307 } else {
3308 SLOGE("Encrypted, default crypt type but can't decrypt");
3309 }
3310 }
3311
Paul Lawrence6bfed202014-07-28 12:47:22 -07003312 /** Corrupt. Allow us to boot into framework, which will detect bad
3313 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003314 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003315 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003316 return 0;
3317}
3318
3319/* Returns type of the password, default, pattern, pin or password.
3320 */
3321int cryptfs_get_password_type(void)
3322{
3323 struct crypt_mnt_ftr crypt_ftr;
3324
3325 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3326 SLOGE("Error getting crypt footer and key\n");
3327 return -1;
3328 }
3329
Paul Lawrence6bfed202014-07-28 12:47:22 -07003330 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3331 return -1;
3332 }
3333
Paul Lawrencef4faa572014-01-29 13:31:03 -08003334 return crypt_ftr.crypt_type;
3335}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003336
Paul Lawrence399317e2014-03-10 13:20:50 -07003337char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003338{
Paul Lawrence399317e2014-03-10 13:20:50 -07003339 struct timespec now;
3340 clock_gettime(CLOCK_MONOTONIC, &now);
3341 if (now.tv_sec < password_expiry_time) {
3342 return password;
3343 } else {
3344 cryptfs_clear_password();
3345 return 0;
3346 }
3347}
3348
3349void cryptfs_clear_password()
3350{
3351 if (password) {
3352 size_t len = strlen(password);
3353 memset(password, 0, len);
3354 free(password);
3355 password = 0;
3356 password_expiry_time = 0;
3357 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003358}