blob: a8211cc9c55b93ec853e1e9d7d3e3d5a370a1a9f [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
23#include <sys/types.h>
Ken Sumralle550f782013-08-20 13:48:23 -070024#include <sys/wait.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080025#include <sys/stat.h>
Paul Lawrencef4faa572014-01-29 13:31:03 -080026#include <ctype.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080027#include <fcntl.h>
Elliott Hughes73737162014-06-25 17:27:42 -070028#include <inttypes.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080029#include <unistd.h>
30#include <stdio.h>
31#include <sys/ioctl.h>
32#include <linux/dm-ioctl.h>
33#include <libgen.h>
34#include <stdlib.h>
35#include <sys/param.h>
36#include <string.h>
37#include <sys/mount.h>
38#include <openssl/evp.h>
39#include <errno.h>
Ken Sumrall3ed82362011-01-28 23:31:16 -080040#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070041#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070042#include <fs_mgr.h>
Paul Lawrence9c58a872014-09-30 09:12:51 -070043#include <time.h>
Rubin Xu85c01f92014-10-13 12:49:54 +010044#include <math.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080045#include "cryptfs.h"
46#define LOG_TAG "Cryptfs"
47#include "cutils/log.h"
48#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070049#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080050#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070051#include <logwrap/logwrap.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070052#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070053#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070054#include "crypto_scrypt.h"
Paul Lawrenceae59fe62014-01-21 08:23:27 -080055#include "ext4_utils.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000056#include "f2fs_sparseblock.h"
Paul Lawrence87999172014-02-20 12:21:31 -080057#include "CheckBattery.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080058#include "Process.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080059
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070060#include <hardware/keymaster.h>
61
Mark Salyzyn3e971272014-01-21 13:27:04 -080062#define UNUSED __attribute__((unused))
63
Mark Salyzyn5eecc442014-02-12 14:16:14 -080064#define UNUSED __attribute__((unused))
65
Ajay Dudani87701e22014-09-17 21:02:52 -070066#ifdef CONFIG_HW_DISK_ENCRYPTION
67#include "cryptfs_hw.h"
68#endif
69
Ken Sumrall8f869aa2010-12-03 03:47:09 -080070#define DM_CRYPT_BUF_SIZE 4096
71
Jason parks70a4b3f2011-01-28 10:10:47 -060072#define HASH_COUNT 2000
73#define KEY_LEN_BYTES 16
74#define IV_LEN_BYTES 16
75
Ken Sumrall29d8da82011-05-18 17:20:07 -070076#define KEY_IN_FOOTER "footer"
77
Paul Lawrencef4faa572014-01-29 13:31:03 -080078// "default_password" encoded into hex (d=0x64 etc)
79#define DEFAULT_PASSWORD "64656661756c745f70617373776f7264"
80
Ken Sumrall29d8da82011-05-18 17:20:07 -070081#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070082#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070083
Ken Sumralle919efe2012-09-29 17:07:41 -070084#define TABLE_LOAD_RETRIES 10
85
Shawn Willden47ba10d2014-09-03 17:07:06 -060086#define RSA_KEY_SIZE 2048
87#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
88#define RSA_EXPONENT 0x10001
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070089
Paul Lawrence8e3f4512014-09-08 10:11:17 -070090#define RETRY_MOUNT_ATTEMPTS 10
91#define RETRY_MOUNT_DELAY_SECONDS 1
92
Ken Sumrall8f869aa2010-12-03 03:47:09 -080093char *me = "cryptfs";
94
Jason parks70a4b3f2011-01-28 10:10:47 -060095static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070096static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060097static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -070098static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -080099
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700100static int keymaster_init(keymaster_device_t **keymaster_dev)
101{
102 int rc;
103
104 const hw_module_t* mod;
105 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
106 if (rc) {
107 ALOGE("could not find any keystore module");
108 goto out;
109 }
110
111 rc = keymaster_open(mod, keymaster_dev);
112 if (rc) {
113 ALOGE("could not open keymaster device in %s (%s)",
114 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
115 goto out;
116 }
117
118 return 0;
119
120out:
121 *keymaster_dev = NULL;
122 return rc;
123}
124
125/* Should we use keymaster? */
126static int keymaster_check_compatibility()
127{
128 keymaster_device_t *keymaster_dev = 0;
129 int rc = 0;
130
131 if (keymaster_init(&keymaster_dev)) {
132 SLOGE("Failed to init keymaster");
133 rc = -1;
134 goto out;
135 }
136
Paul Lawrence8c008392014-05-06 14:02:48 -0700137 SLOGI("keymaster version is %d", keymaster_dev->common.module->module_api_version);
138
139 if (keymaster_dev->common.module->module_api_version
140 < KEYMASTER_MODULE_API_VERSION_0_3) {
141 rc = 0;
142 goto out;
143 }
144
Shawn Willden7c49ab02014-10-30 08:12:32 -0600145 if (!(keymaster_dev->flags & KEYMASTER_SOFTWARE_ONLY) &&
146 (keymaster_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE)) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700147 rc = 1;
148 }
149
150out:
151 keymaster_close(keymaster_dev);
152 return rc;
153}
154
155/* Create a new keymaster key and store it in this footer */
156static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
157{
158 uint8_t* key = 0;
159 keymaster_device_t *keymaster_dev = 0;
160
161 if (keymaster_init(&keymaster_dev)) {
162 SLOGE("Failed to init keymaster");
163 return -1;
164 }
165
166 int rc = 0;
167
168 keymaster_rsa_keygen_params_t params;
169 memset(&params, '\0', sizeof(params));
Shawn Willden47ba10d2014-09-03 17:07:06 -0600170 params.public_exponent = RSA_EXPONENT;
171 params.modulus_size = RSA_KEY_SIZE;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700172
173 size_t key_size;
174 if (keymaster_dev->generate_keypair(keymaster_dev, TYPE_RSA, &params,
175 &key, &key_size)) {
176 SLOGE("Failed to generate keypair");
177 rc = -1;
178 goto out;
179 }
180
181 if (key_size > KEYMASTER_BLOB_SIZE) {
182 SLOGE("Keymaster key too large for crypto footer");
183 rc = -1;
184 goto out;
185 }
186
187 memcpy(ftr->keymaster_blob, key, key_size);
188 ftr->keymaster_blob_size = key_size;
189
190out:
191 keymaster_close(keymaster_dev);
192 free(key);
193 return rc;
194}
195
Shawn Willdene17a9c42014-09-08 13:04:08 -0600196/* This signs the given object using the keymaster key. */
197static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600198 const unsigned char *object,
199 const size_t object_size,
200 unsigned char **signature,
201 size_t *signature_size)
202{
203 int rc = 0;
204 keymaster_device_t *keymaster_dev = 0;
205 if (keymaster_init(&keymaster_dev)) {
206 SLOGE("Failed to init keymaster");
207 return -1;
208 }
209
210 /* We currently set the digest type to DIGEST_NONE because it's the
211 * only supported value for keymaster. A similar issue exists with
212 * PADDING_NONE. Long term both of these should likely change.
213 */
214 keymaster_rsa_sign_params_t params;
215 params.digest_type = DIGEST_NONE;
216 params.padding_type = PADDING_NONE;
217
218 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600219 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600220 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600221
Shawn Willdene17a9c42014-09-08 13:04:08 -0600222 // To sign a message with RSA, the message must satisfy two
223 // constraints:
224 //
225 // 1. The message, when interpreted as a big-endian numeric value, must
226 // be strictly less than the public modulus of the RSA key. Note
227 // that because the most significant bit of the public modulus is
228 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
229 // key), an n-bit message with most significant bit 0 always
230 // satisfies this requirement.
231 //
232 // 2. The message must have the same length in bits as the public
233 // modulus of the RSA key. This requirement isn't mathematically
234 // necessary, but is necessary to ensure consistency in
235 // implementations.
236 switch (ftr->kdf_type) {
237 case KDF_SCRYPT_KEYMASTER_UNPADDED:
238 // This is broken: It produces a message which is shorter than
239 // the public modulus, failing criterion 2.
240 memcpy(to_sign, object, object_size);
241 to_sign_size = object_size;
242 SLOGI("Signing unpadded object");
243 break;
244 case KDF_SCRYPT_KEYMASTER_BADLY_PADDED:
245 // This is broken: Since the value of object is uniformly
246 // distributed, it produces a message that is larger than the
247 // public modulus with probability 0.25.
248 memcpy(to_sign, object, min(RSA_KEY_SIZE_BYTES, object_size));
249 SLOGI("Signing end-padded object");
250 break;
251 case KDF_SCRYPT_KEYMASTER:
252 // This ensures the most significant byte of the signed message
253 // is zero. We could have zero-padded to the left instead, but
254 // this approach is slightly more robust against changes in
255 // object size. However, it's still broken (but not unusably
256 // so) because we really should be using a proper RSA padding
257 // function, such as OAEP.
258 //
259 // TODO(paullawrence): When keymaster 0.4 is available, change
260 // this to use the padding options it provides.
261 memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
262 SLOGI("Signing safely-padded object");
263 break;
264 default:
265 SLOGE("Unknown KDF type %d", ftr->kdf_type);
266 return -1;
267 }
268
Shawn Willden47ba10d2014-09-03 17:07:06 -0600269 rc = keymaster_dev->sign_data(keymaster_dev,
270 &params,
271 ftr->keymaster_blob,
272 ftr->keymaster_blob_size,
273 to_sign,
Shawn Willdene17a9c42014-09-08 13:04:08 -0600274 to_sign_size,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600275 signature,
276 signature_size);
277
278 keymaster_close(keymaster_dev);
279 return rc;
280}
281
Paul Lawrence399317e2014-03-10 13:20:50 -0700282/* Store password when userdata is successfully decrypted and mounted.
283 * Cleared by cryptfs_clear_password
284 *
285 * To avoid a double prompt at boot, we need to store the CryptKeeper
286 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
287 * Since the entire framework is torn down and rebuilt after encryption,
288 * we have to use a daemon or similar to store the password. Since vold
289 * is secured against IPC except from system processes, it seems a reasonable
290 * place to store this.
291 *
292 * password should be cleared once it has been used.
293 *
294 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800295 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700296static char* password = 0;
297static int password_expiry_time = 0;
298static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800299
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800300extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800301
Paul Lawrence87999172014-02-20 12:21:31 -0800302enum RebootType {reboot, recovery, shutdown};
303static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700304{
Paul Lawrence87999172014-02-20 12:21:31 -0800305 switch(rt) {
306 case reboot:
307 property_set(ANDROID_RB_PROPERTY, "reboot");
308 break;
309
310 case recovery:
311 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
312 break;
313
314 case shutdown:
315 property_set(ANDROID_RB_PROPERTY, "shutdown");
316 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700317 }
Paul Lawrence87999172014-02-20 12:21:31 -0800318
Ken Sumralladfba362013-06-04 16:37:52 -0700319 sleep(20);
320
321 /* Shouldn't get here, reboot should happen before sleep times out */
322 return;
323}
324
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800325static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
326{
327 memset(io, 0, dataSize);
328 io->data_size = dataSize;
329 io->data_start = sizeof(struct dm_ioctl);
330 io->version[0] = 4;
331 io->version[1] = 0;
332 io->version[2] = 0;
333 io->flags = flags;
334 if (name) {
335 strncpy(io->name, name, sizeof(io->name));
336 }
337}
338
Kenny Rootc4c70f12013-06-14 12:11:38 -0700339/**
340 * Gets the default device scrypt parameters for key derivation time tuning.
341 * The parameters should lead to about one second derivation time for the
342 * given device.
343 */
344static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
345 const int default_params[] = SCRYPT_DEFAULTS;
346 int params[] = SCRYPT_DEFAULTS;
347 char paramstr[PROPERTY_VALUE_MAX];
348 char *token;
349 char *saveptr;
350 int i;
351
352 property_get(SCRYPT_PROP, paramstr, "");
353 if (paramstr[0] != '\0') {
354 /*
355 * The token we're looking for should be three integers separated by
356 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
357 */
Kenny Root2947e342013-08-14 15:54:49 -0700358 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
359 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700360 i++, token = strtok_r(NULL, ":", &saveptr)) {
361 char *endptr;
362 params[i] = strtol(token, &endptr, 10);
363
364 /*
365 * Check that there was a valid number and it's 8-bit. If not,
366 * break out and the end check will take the default values.
367 */
368 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
369 break;
370 }
371 }
372
373 /*
374 * If there were not enough tokens or a token was malformed (not an
375 * integer), it will end up here and the default parameters can be
376 * taken.
377 */
378 if ((i != 3) || (token != NULL)) {
379 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
380 memcpy(params, default_params, sizeof(params));
381 }
382 }
383
384 ftr->N_factor = params[0];
385 ftr->r_factor = params[1];
386 ftr->p_factor = params[2];
387}
388
Ken Sumrall3ed82362011-01-28 23:31:16 -0800389static unsigned int get_fs_size(char *dev)
390{
391 int fd, block_size;
392 struct ext4_super_block sb;
393 off64_t len;
394
395 if ((fd = open(dev, O_RDONLY)) < 0) {
396 SLOGE("Cannot open device to get filesystem size ");
397 return 0;
398 }
399
400 if (lseek64(fd, 1024, SEEK_SET) < 0) {
401 SLOGE("Cannot seek to superblock");
402 return 0;
403 }
404
405 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
406 SLOGE("Cannot read superblock");
407 return 0;
408 }
409
410 close(fd);
411
Daniel Rosenberge82df162014-08-15 22:19:23 +0000412 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
413 SLOGE("Not a valid ext4 superblock");
414 return 0;
415 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800416 block_size = 1024 << sb.s_log_block_size;
417 /* compute length in bytes */
418 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
419
420 /* return length in sectors */
421 return (unsigned int) (len / 512);
422}
423
Ken Sumrall160b4d62013-04-22 12:15:39 -0700424static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
425{
426 static int cached_data = 0;
427 static off64_t cached_off = 0;
428 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
429 int fd;
430 char key_loc[PROPERTY_VALUE_MAX];
431 char real_blkdev[PROPERTY_VALUE_MAX];
432 unsigned int nr_sec;
433 int rc = -1;
434
435 if (!cached_data) {
436 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
437
438 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
439 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
440 SLOGE("Cannot open real block device %s\n", real_blkdev);
441 return -1;
442 }
443
444 if ((nr_sec = get_blkdev_size(fd))) {
445 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
446 * encryption info footer and key, and plenty of bytes to spare for future
447 * growth.
448 */
449 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
450 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
451 cached_data = 1;
452 } else {
453 SLOGE("Cannot get size of block device %s\n", real_blkdev);
454 }
455 close(fd);
456 } else {
457 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
458 cached_off = 0;
459 cached_data = 1;
460 }
461 }
462
463 if (cached_data) {
464 if (metadata_fname) {
465 *metadata_fname = cached_metadata_fname;
466 }
467 if (off) {
468 *off = cached_off;
469 }
470 rc = 0;
471 }
472
473 return rc;
474}
475
Ken Sumralle8744072011-01-18 22:01:55 -0800476/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800477 * update the failed mount count but not change the key.
478 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700479static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800480{
481 int fd;
482 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700483 /* starting_off is set to the SEEK_SET offset
484 * where the crypto structure starts
485 */
486 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800487 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700488 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700489 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800490
Ken Sumrall160b4d62013-04-22 12:15:39 -0700491 if (get_crypt_ftr_info(&fname, &starting_off)) {
492 SLOGE("Unable to get crypt_ftr_info\n");
493 return -1;
494 }
495 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700496 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700497 return -1;
498 }
Ken Sumralle550f782013-08-20 13:48:23 -0700499 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
500 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700501 return -1;
502 }
503
504 /* Seek to the start of the crypt footer */
505 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
506 SLOGE("Cannot seek to real block device footer\n");
507 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800508 }
509
510 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
511 SLOGE("Cannot write real block device footer\n");
512 goto errout;
513 }
514
Ken Sumrall3be890f2011-09-14 16:53:46 -0700515 fstat(fd, &statbuf);
516 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700517 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700518 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800519 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800520 goto errout;
521 }
522 }
523
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800524 /* Success! */
525 rc = 0;
526
527errout:
528 close(fd);
529 return rc;
530
531}
532
Ken Sumrall160b4d62013-04-22 12:15:39 -0700533static inline int unix_read(int fd, void* buff, int len)
534{
535 return TEMP_FAILURE_RETRY(read(fd, buff, len));
536}
537
538static inline int unix_write(int fd, const void* buff, int len)
539{
540 return TEMP_FAILURE_RETRY(write(fd, buff, len));
541}
542
543static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
544{
545 memset(pdata, 0, len);
546 pdata->persist_magic = PERSIST_DATA_MAGIC;
547 pdata->persist_valid_entries = 0;
548}
549
550/* A routine to update the passed in crypt_ftr to the lastest version.
551 * fd is open read/write on the device that holds the crypto footer and persistent
552 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
553 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
554 */
555static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
556{
Kenny Root7434b312013-06-14 11:29:53 -0700557 int orig_major = crypt_ftr->major_version;
558 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700559
Kenny Root7434b312013-06-14 11:29:53 -0700560 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
561 struct crypt_persist_data *pdata;
562 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700563
Kenny Rootc4c70f12013-06-14 12:11:38 -0700564 SLOGW("upgrading crypto footer to 1.1");
565
Kenny Root7434b312013-06-14 11:29:53 -0700566 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
567 if (pdata == NULL) {
568 SLOGE("Cannot allocate persisent data\n");
569 return;
570 }
571 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
572
573 /* Need to initialize the persistent data area */
574 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
575 SLOGE("Cannot seek to persisent data offset\n");
576 return;
577 }
578 /* Write all zeros to the first copy, making it invalid */
579 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
580
581 /* Write a valid but empty structure to the second copy */
582 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
583 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
584
585 /* Update the footer */
586 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
587 crypt_ftr->persist_data_offset[0] = pdata_offset;
588 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
589 crypt_ftr->minor_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700590 }
591
Paul Lawrencef4faa572014-01-29 13:31:03 -0800592 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700593 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800594 /* But keep the old kdf_type.
595 * It will get updated later to KDF_SCRYPT after the password has been verified.
596 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700597 crypt_ftr->kdf_type = KDF_PBKDF2;
598 get_device_scrypt_params(crypt_ftr);
599 crypt_ftr->minor_version = 2;
600 }
601
Paul Lawrencef4faa572014-01-29 13:31:03 -0800602 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
603 SLOGW("upgrading crypto footer to 1.3");
604 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
605 crypt_ftr->minor_version = 3;
606 }
607
Kenny Root7434b312013-06-14 11:29:53 -0700608 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
609 if (lseek64(fd, offset, SEEK_SET) == -1) {
610 SLOGE("Cannot seek to crypt footer\n");
611 return;
612 }
613 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700614 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700615}
616
617
618static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800619{
620 int fd;
621 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700622 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800623 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700624 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700625 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800626
Ken Sumrall160b4d62013-04-22 12:15:39 -0700627 if (get_crypt_ftr_info(&fname, &starting_off)) {
628 SLOGE("Unable to get crypt_ftr_info\n");
629 return -1;
630 }
631 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700632 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700633 return -1;
634 }
635 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700636 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700637 return -1;
638 }
639
640 /* Make sure it's 16 Kbytes in length */
641 fstat(fd, &statbuf);
642 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
643 SLOGE("footer file %s is not the expected size!\n", fname);
644 goto errout;
645 }
646
647 /* Seek to the start of the crypt footer */
648 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
649 SLOGE("Cannot seek to real block device footer\n");
650 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800651 }
652
653 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
654 SLOGE("Cannot read real block device footer\n");
655 goto errout;
656 }
657
658 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700659 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800660 goto errout;
661 }
662
Kenny Rootc96a5f82013-06-14 12:08:28 -0700663 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
664 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
665 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800666 goto errout;
667 }
668
Kenny Rootc96a5f82013-06-14 12:08:28 -0700669 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
670 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
671 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800672 }
673
Ken Sumrall160b4d62013-04-22 12:15:39 -0700674 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
675 * copy on disk before returning.
676 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700677 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700678 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800679 }
680
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800681 /* Success! */
682 rc = 0;
683
684errout:
685 close(fd);
686 return rc;
687}
688
Ken Sumrall160b4d62013-04-22 12:15:39 -0700689static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
690{
691 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
692 crypt_ftr->persist_data_offset[1]) {
693 SLOGE("Crypt_ftr persist data regions overlap");
694 return -1;
695 }
696
697 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
698 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
699 return -1;
700 }
701
702 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
703 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
704 CRYPT_FOOTER_OFFSET) {
705 SLOGE("Persistent data extends past crypto footer");
706 return -1;
707 }
708
709 return 0;
710}
711
712static int load_persistent_data(void)
713{
714 struct crypt_mnt_ftr crypt_ftr;
715 struct crypt_persist_data *pdata = NULL;
716 char encrypted_state[PROPERTY_VALUE_MAX];
717 char *fname;
718 int found = 0;
719 int fd;
720 int ret;
721 int i;
722
723 if (persist_data) {
724 /* Nothing to do, we've already loaded or initialized it */
725 return 0;
726 }
727
728
729 /* If not encrypted, just allocate an empty table and initialize it */
730 property_get("ro.crypto.state", encrypted_state, "");
731 if (strcmp(encrypted_state, "encrypted") ) {
732 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
733 if (pdata) {
734 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
735 persist_data = pdata;
736 return 0;
737 }
738 return -1;
739 }
740
741 if(get_crypt_ftr_and_key(&crypt_ftr)) {
742 return -1;
743 }
744
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700745 if ((crypt_ftr.major_version < 1)
746 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700747 SLOGE("Crypt_ftr version doesn't support persistent data");
748 return -1;
749 }
750
751 if (get_crypt_ftr_info(&fname, NULL)) {
752 return -1;
753 }
754
755 ret = validate_persistent_data_storage(&crypt_ftr);
756 if (ret) {
757 return -1;
758 }
759
760 fd = open(fname, O_RDONLY);
761 if (fd < 0) {
762 SLOGE("Cannot open %s metadata file", fname);
763 return -1;
764 }
765
766 if (persist_data == NULL) {
767 pdata = malloc(crypt_ftr.persist_data_size);
768 if (pdata == NULL) {
769 SLOGE("Cannot allocate memory for persistent data");
770 goto err;
771 }
772 }
773
774 for (i = 0; i < 2; i++) {
775 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
776 SLOGE("Cannot seek to read persistent data on %s", fname);
777 goto err2;
778 }
779 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
780 SLOGE("Error reading persistent data on iteration %d", i);
781 goto err2;
782 }
783 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
784 found = 1;
785 break;
786 }
787 }
788
789 if (!found) {
790 SLOGI("Could not find valid persistent data, creating");
791 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
792 }
793
794 /* Success */
795 persist_data = pdata;
796 close(fd);
797 return 0;
798
799err2:
800 free(pdata);
801
802err:
803 close(fd);
804 return -1;
805}
806
807static int save_persistent_data(void)
808{
809 struct crypt_mnt_ftr crypt_ftr;
810 struct crypt_persist_data *pdata;
811 char *fname;
812 off64_t write_offset;
813 off64_t erase_offset;
814 int found = 0;
815 int fd;
816 int ret;
817
818 if (persist_data == NULL) {
819 SLOGE("No persistent data to save");
820 return -1;
821 }
822
823 if(get_crypt_ftr_and_key(&crypt_ftr)) {
824 return -1;
825 }
826
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700827 if ((crypt_ftr.major_version < 1)
828 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700829 SLOGE("Crypt_ftr version doesn't support persistent data");
830 return -1;
831 }
832
833 ret = validate_persistent_data_storage(&crypt_ftr);
834 if (ret) {
835 return -1;
836 }
837
838 if (get_crypt_ftr_info(&fname, NULL)) {
839 return -1;
840 }
841
842 fd = open(fname, O_RDWR);
843 if (fd < 0) {
844 SLOGE("Cannot open %s metadata file", fname);
845 return -1;
846 }
847
848 pdata = malloc(crypt_ftr.persist_data_size);
849 if (pdata == NULL) {
850 SLOGE("Cannot allocate persistant data");
851 goto err;
852 }
853
854 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
855 SLOGE("Cannot seek to read persistent data on %s", fname);
856 goto err2;
857 }
858
859 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
860 SLOGE("Error reading persistent data before save");
861 goto err2;
862 }
863
864 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
865 /* The first copy is the curent valid copy, so write to
866 * the second copy and erase this one */
867 write_offset = crypt_ftr.persist_data_offset[1];
868 erase_offset = crypt_ftr.persist_data_offset[0];
869 } else {
870 /* The second copy must be the valid copy, so write to
871 * the first copy, and erase the second */
872 write_offset = crypt_ftr.persist_data_offset[0];
873 erase_offset = crypt_ftr.persist_data_offset[1];
874 }
875
876 /* Write the new copy first, if successful, then erase the old copy */
877 if (lseek(fd, write_offset, SEEK_SET) < 0) {
878 SLOGE("Cannot seek to write persistent data");
879 goto err2;
880 }
881 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
882 (int) crypt_ftr.persist_data_size) {
883 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
884 SLOGE("Cannot seek to erase previous persistent data");
885 goto err2;
886 }
887 fsync(fd);
888 memset(pdata, 0, crypt_ftr.persist_data_size);
889 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
890 (int) crypt_ftr.persist_data_size) {
891 SLOGE("Cannot write to erase previous persistent data");
892 goto err2;
893 }
894 fsync(fd);
895 } else {
896 SLOGE("Cannot write to save persistent data");
897 goto err2;
898 }
899
900 /* Success */
901 free(pdata);
902 close(fd);
903 return 0;
904
905err2:
906 free(pdata);
907err:
908 close(fd);
909 return -1;
910}
911
Paul Lawrencef4faa572014-01-29 13:31:03 -0800912static int hexdigit (char c)
913{
914 if (c >= '0' && c <= '9') return c - '0';
915 c = tolower(c);
916 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
917 return -1;
918}
919
920static unsigned char* convert_hex_ascii_to_key(const char* master_key_ascii,
921 unsigned int* out_keysize)
922{
923 unsigned int i;
924 *out_keysize = 0;
925
926 size_t size = strlen (master_key_ascii);
927 if (size % 2) {
928 SLOGE("Trying to convert ascii string of odd length");
929 return NULL;
930 }
931
932 unsigned char* master_key = (unsigned char*) malloc(size / 2);
933 if (master_key == 0) {
934 SLOGE("Cannot allocate");
935 return NULL;
936 }
937
938 for (i = 0; i < size; i += 2) {
939 int high_nibble = hexdigit (master_key_ascii[i]);
940 int low_nibble = hexdigit (master_key_ascii[i + 1]);
941
942 if(high_nibble < 0 || low_nibble < 0) {
943 SLOGE("Invalid hex string");
944 free (master_key);
945 return NULL;
946 }
947
948 master_key[*out_keysize] = high_nibble * 16 + low_nibble;
949 (*out_keysize)++;
950 }
951
952 return master_key;
953}
954
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800955/* Convert a binary key of specified length into an ascii hex string equivalent,
956 * without the leading 0x and with null termination
957 */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800958static void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800959 char *master_key_ascii)
960{
961 unsigned int i, a;
962 unsigned char nibble;
963
964 for (i=0, a=0; i<keysize; i++, a+=2) {
965 /* For each byte, write out two ascii hex digits */
966 nibble = (master_key[i] >> 4) & 0xf;
967 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
968
969 nibble = master_key[i] & 0xf;
970 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
971 }
972
973 /* Add the null termination */
974 master_key_ascii[a] = '\0';
975
976}
977
Ken Sumralldb5e0262013-02-05 17:39:48 -0800978static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
979 char *real_blk_name, const char *name, int fd,
980 char *extra_params)
981{
982 char buffer[DM_CRYPT_BUF_SIZE];
983 struct dm_ioctl *io;
984 struct dm_target_spec *tgt;
985 char *crypt_params;
986 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
987 int i;
988
989 io = (struct dm_ioctl *) buffer;
990
991 /* Load the mapping table for this device */
992 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
993
994 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
995 io->target_count = 1;
996 tgt->status = 0;
997 tgt->sector_start = 0;
998 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -0700999#ifdef CONFIG_HW_DISK_ENCRYPTION
1000 strlcpy(tgt->target_type, "req-crypt", DM_MAX_TYPE_NAME);
1001#else
1002 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1003#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001004
1005 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
1006 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1007 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
1008 master_key_ascii, real_blk_name, extra_params);
1009 crypt_params += strlen(crypt_params) + 1;
1010 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1011 tgt->next = crypt_params - buffer;
1012
1013 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1014 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
1015 break;
1016 }
1017 usleep(500000);
1018 }
1019
1020 if (i == TABLE_LOAD_RETRIES) {
1021 /* We failed to load the table, return an error */
1022 return -1;
1023 } else {
1024 return i + 1;
1025 }
1026}
1027
1028
1029static int get_dm_crypt_version(int fd, const char *name, int *version)
1030{
1031 char buffer[DM_CRYPT_BUF_SIZE];
1032 struct dm_ioctl *io;
1033 struct dm_target_versions *v;
1034 int i;
1035
1036 io = (struct dm_ioctl *) buffer;
1037
1038 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1039
1040 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1041 return -1;
1042 }
1043
1044 /* Iterate over the returned versions, looking for name of "crypt".
1045 * When found, get and return the version.
1046 */
1047 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1048 while (v->next) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001049#ifdef CONFIG_HW_DISK_ENCRYPTION
1050 if(!strcmp(v->name, "crypt") || !strcmp(v->name, "req-crypt")) {
1051#else
Ken Sumralldb5e0262013-02-05 17:39:48 -08001052 if (! strcmp(v->name, "crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001053#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001054 /* We found the crypt driver, return the version, and get out */
1055 version[0] = v->version[0];
1056 version[1] = v->version[1];
1057 version[2] = v->version[2];
1058 return 0;
1059 }
1060 v = (struct dm_target_versions *)(((char *)v) + v->next);
1061 }
1062
1063 return -1;
1064}
1065
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001066static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -07001067 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001068{
1069 char buffer[DM_CRYPT_BUF_SIZE];
1070 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
1071 char *crypt_params;
1072 struct dm_ioctl *io;
1073 struct dm_target_spec *tgt;
1074 unsigned int minor;
Ajay Dudani87701e22014-09-17 21:02:52 -07001075 int fd=0;
Ken Sumralle919efe2012-09-29 17:07:41 -07001076 int i;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001077 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001078 int version[3];
1079 char *extra_params;
1080 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001081
1082 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1083 SLOGE("Cannot open device-mapper\n");
1084 goto errout;
1085 }
1086
1087 io = (struct dm_ioctl *) buffer;
1088
1089 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1090 if (ioctl(fd, DM_DEV_CREATE, io)) {
1091 SLOGE("Cannot create dm-crypt device\n");
1092 goto errout;
1093 }
1094
1095 /* Get the device status, in particular, the name of it's device file */
1096 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1097 if (ioctl(fd, DM_DEV_STATUS, io)) {
1098 SLOGE("Cannot retrieve dm-crypt device status\n");
1099 goto errout;
1100 }
1101 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1102 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1103
Ken Sumralldb5e0262013-02-05 17:39:48 -08001104 extra_params = "";
1105 if (! get_dm_crypt_version(fd, name, version)) {
1106 /* Support for allow_discards was added in version 1.11.0 */
1107 if ((version[0] >= 2) ||
1108 ((version[0] == 1) && (version[1] >= 11))) {
1109 extra_params = "1 allow_discards";
1110 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1111 }
Ken Sumralle919efe2012-09-29 17:07:41 -07001112 }
1113
Ken Sumralldb5e0262013-02-05 17:39:48 -08001114 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1115 fd, extra_params);
1116 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001117 SLOGE("Cannot load dm-crypt mapping table.\n");
1118 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001119 } else if (load_count > 1) {
1120 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001121 }
1122
1123 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -08001124 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001125
1126 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1127 SLOGE("Cannot resume the dm-crypt device\n");
1128 goto errout;
1129 }
1130
1131 /* We made it here with no errors. Woot! */
1132 retval = 0;
1133
1134errout:
1135 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1136
1137 return retval;
1138}
1139
Ken Sumrall29d8da82011-05-18 17:20:07 -07001140static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001141{
1142 int fd;
1143 char buffer[DM_CRYPT_BUF_SIZE];
1144 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001145 int retval = -1;
1146
1147 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1148 SLOGE("Cannot open device-mapper\n");
1149 goto errout;
1150 }
1151
1152 io = (struct dm_ioctl *) buffer;
1153
1154 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1155 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1156 SLOGE("Cannot remove dm-crypt device\n");
1157 goto errout;
1158 }
1159
1160 /* We made it here with no errors. Woot! */
1161 retval = 0;
1162
1163errout:
1164 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1165
1166 return retval;
1167
1168}
1169
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001170static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001171 unsigned char *ikey, void *params UNUSED)
1172{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001173 SLOGI("Using pbkdf2 for cryptfs KDF");
1174
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001175 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001176 unsigned int keysize;
1177 char* master_key = (char*)convert_hex_ascii_to_key(passwd, &keysize);
1178 if (!master_key) return -1;
1179 PKCS5_PBKDF2_HMAC_SHA1(master_key, keysize, salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001180 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001181
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001182 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001183 free (master_key);
1184 return 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001185}
1186
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001187static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001188 unsigned char *ikey, void *params)
1189{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001190 SLOGI("Using scrypt for cryptfs KDF");
1191
Kenny Rootc4c70f12013-06-14 12:11:38 -07001192 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1193
1194 int N = 1 << ftr->N_factor;
1195 int r = 1 << ftr->r_factor;
1196 int p = 1 << ftr->p_factor;
1197
1198 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001199 unsigned int keysize;
1200 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &keysize);
1201 if (!master_key) return -1;
1202 crypto_scrypt(master_key, keysize, salt, SALT_LEN, N, r, p, ikey,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001203 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001204
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001205 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001206 free (master_key);
1207 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001208}
1209
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001210static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1211 unsigned char *ikey, void *params)
1212{
1213 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1214
1215 int rc;
1216 unsigned int key_size;
1217 size_t signature_size;
1218 unsigned char* signature;
1219 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1220
1221 int N = 1 << ftr->N_factor;
1222 int r = 1 << ftr->r_factor;
1223 int p = 1 << ftr->p_factor;
1224
1225 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &key_size);
1226 if (!master_key) {
1227 SLOGE("Failed to convert passwd from hex");
1228 return -1;
1229 }
1230
1231 rc = crypto_scrypt(master_key, key_size, salt, SALT_LEN,
1232 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1233 memset(master_key, 0, key_size);
1234 free(master_key);
1235
1236 if (rc) {
1237 SLOGE("scrypt failed");
1238 return -1;
1239 }
1240
Shawn Willdene17a9c42014-09-08 13:04:08 -06001241 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1242 &signature, &signature_size)) {
1243 SLOGE("Signing failed");
1244 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001245 }
1246
1247 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1248 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1249 free(signature);
1250
1251 if (rc) {
1252 SLOGE("scrypt failed");
1253 return -1;
1254 }
1255
1256 return 0;
1257}
1258
1259static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1260 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001261 unsigned char *encrypted_master_key,
1262 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001263{
1264 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1265 EVP_CIPHER_CTX e_ctx;
1266 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001267 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001268
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001269 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001270 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001271
1272 switch (crypt_ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001273 case KDF_SCRYPT_KEYMASTER_UNPADDED:
1274 case KDF_SCRYPT_KEYMASTER_BADLY_PADDED:
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001275 case KDF_SCRYPT_KEYMASTER:
1276 if (keymaster_create_key(crypt_ftr)) {
1277 SLOGE("keymaster_create_key failed");
1278 return -1;
1279 }
1280
1281 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1282 SLOGE("scrypt failed");
1283 return -1;
1284 }
1285 break;
1286
1287 case KDF_SCRYPT:
1288 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1289 SLOGE("scrypt failed");
1290 return -1;
1291 }
1292 break;
1293
1294 default:
1295 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001296 return -1;
1297 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001298
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001299 /* Initialize the decryption engine */
1300 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1301 SLOGE("EVP_EncryptInit failed\n");
1302 return -1;
1303 }
1304 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001305
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001306 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001307 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
1308 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001309 SLOGE("EVP_EncryptUpdate failed\n");
1310 return -1;
1311 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001312 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001313 SLOGE("EVP_EncryptFinal failed\n");
1314 return -1;
1315 }
1316
1317 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1318 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1319 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001320 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001321
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001322 /* Store the scrypt of the intermediate key, so we can validate if it's a
1323 password error or mount error when things go wrong.
1324 Note there's no need to check for errors, since if this is incorrect, we
1325 simply won't wipe userdata, which is the correct default behavior
1326 */
1327 int N = 1 << crypt_ftr->N_factor;
1328 int r = 1 << crypt_ftr->r_factor;
1329 int p = 1 << crypt_ftr->p_factor;
1330
1331 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1332 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1333 crypt_ftr->scrypted_intermediate_key,
1334 sizeof(crypt_ftr->scrypted_intermediate_key));
1335
1336 if (rc) {
1337 SLOGE("encrypt_master_key: crypto_scrypt failed");
1338 }
1339
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001340 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001341}
1342
JP Abgrall7bdfa522013-11-15 13:42:56 -08001343static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001344 unsigned char *encrypted_master_key,
1345 unsigned char *decrypted_master_key,
1346 kdf_func kdf, void *kdf_params,
1347 unsigned char** intermediate_key,
1348 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001349{
1350 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 -08001351 EVP_CIPHER_CTX d_ctx;
1352 int decrypted_len, final_len;
1353
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001354 /* Turn the password into an intermediate key and IV that can decrypt the
1355 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001356 if (kdf(passwd, salt, ikey, kdf_params)) {
1357 SLOGE("kdf failed");
1358 return -1;
1359 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001360
1361 /* Initialize the decryption engine */
1362 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1363 return -1;
1364 }
1365 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1366 /* Decrypt the master key */
1367 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1368 encrypted_master_key, KEY_LEN_BYTES)) {
1369 return -1;
1370 }
1371 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1372 return -1;
1373 }
1374
1375 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1376 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001377 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001378
1379 /* Copy intermediate key if needed by params */
1380 if (intermediate_key && intermediate_key_size) {
1381 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1382 if (intermediate_key) {
1383 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1384 *intermediate_key_size = KEY_LEN_BYTES;
1385 }
1386 }
1387
1388 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001389}
1390
Kenny Rootc4c70f12013-06-14 12:11:38 -07001391static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001392{
Shawn Willdene17a9c42014-09-08 13:04:08 -06001393 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER_UNPADDED ||
1394 ftr->kdf_type == KDF_SCRYPT_KEYMASTER_BADLY_PADDED ||
1395 ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001396 *kdf = scrypt_keymaster;
1397 *kdf_params = ftr;
1398 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001399 *kdf = scrypt;
1400 *kdf_params = ftr;
1401 } else {
1402 *kdf = pbkdf2;
1403 *kdf_params = NULL;
1404 }
1405}
1406
JP Abgrall7bdfa522013-11-15 13:42:56 -08001407static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001408 struct crypt_mnt_ftr *crypt_ftr,
1409 unsigned char** intermediate_key,
1410 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001411{
1412 kdf_func kdf;
1413 void *kdf_params;
1414 int ret;
1415
1416 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001417 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1418 decrypted_master_key, kdf, kdf_params,
1419 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001420 if (ret != 0) {
1421 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001422 }
1423
1424 return ret;
1425}
1426
1427static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1428 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001429 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001430 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001431 EVP_CIPHER_CTX e_ctx;
1432 int encrypted_len, final_len;
1433
1434 /* Get some random bits for a key */
1435 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001436 read(fd, key_buf, sizeof(key_buf));
1437 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001438 close(fd);
1439
1440 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001441 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001442}
1443
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001444static int wait_and_unmount(char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001445{
Greg Hackmann955653e2014-09-24 14:55:20 -07001446 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001447#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001448
1449 /* Now umount the tmpfs filesystem */
1450 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001451 if (umount(mountpoint) == 0) {
1452 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001453 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001454
1455 if (errno == EINVAL) {
1456 /* EINVAL is returned if the directory is not a mountpoint,
1457 * i.e. there is no filesystem mounted there. So just get out.
1458 */
1459 break;
1460 }
1461
1462 err = errno;
1463
1464 /* If allowed, be increasingly aggressive before the last two retries */
1465 if (kill) {
1466 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1467 SLOGW("sending SIGHUP to processes with open files\n");
1468 vold_killProcessesWithOpenFiles(mountpoint, 1);
1469 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1470 SLOGW("sending SIGKILL to processes with open files\n");
1471 vold_killProcessesWithOpenFiles(mountpoint, 2);
1472 }
1473 }
1474
1475 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001476 }
1477
1478 if (i < WAIT_UNMOUNT_COUNT) {
1479 SLOGD("unmounting %s succeeded\n", mountpoint);
1480 rc = 0;
1481 } else {
jessica_yu3f14fe42014-09-22 15:57:40 +08001482 vold_killProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001483 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001484 rc = -1;
1485 }
1486
1487 return rc;
1488}
1489
Ken Sumrallc5872692013-05-14 15:26:31 -07001490#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001491static int prep_data_fs(void)
1492{
1493 int i;
1494
1495 /* Do the prep of the /data filesystem */
1496 property_set("vold.post_fs_data_done", "0");
1497 property_set("vold.decrypt", "trigger_post_fs_data");
1498 SLOGD("Just triggered post_fs_data\n");
1499
Ken Sumrallc5872692013-05-14 15:26:31 -07001500 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001501 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001502 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001503
1504 property_get("vold.post_fs_data_done", p, "0");
1505 if (*p == '1') {
1506 break;
1507 } else {
1508 usleep(250000);
1509 }
1510 }
1511 if (i == DATA_PREP_TIMEOUT) {
1512 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001513 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001514 return -1;
1515 } else {
1516 SLOGD("post_fs_data done\n");
1517 return 0;
1518 }
1519}
1520
Paul Lawrence74f29f12014-08-28 15:54:10 -07001521static void cryptfs_set_corrupt()
1522{
1523 // Mark the footer as bad
1524 struct crypt_mnt_ftr crypt_ftr;
1525 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1526 SLOGE("Failed to get crypto footer - panic");
1527 return;
1528 }
1529
1530 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1531 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1532 SLOGE("Failed to set crypto footer - panic");
1533 return;
1534 }
1535}
1536
1537static void cryptfs_trigger_restart_min_framework()
1538{
1539 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1540 SLOGE("Failed to mount tmpfs on data - panic");
1541 return;
1542 }
1543
1544 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1545 SLOGE("Failed to trigger post fs data - panic");
1546 return;
1547 }
1548
1549 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1550 SLOGE("Failed to trigger restart min framework - panic");
1551 return;
1552 }
1553}
1554
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001555/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001556static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001557{
1558 char fs_type[32];
1559 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001560 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001561 char fs_options[256];
1562 unsigned long mnt_flags;
1563 struct stat statbuf;
1564 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001565 static int restart_successful = 0;
1566
1567 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001568 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001569 SLOGE("Encrypted filesystem not validated, aborting");
1570 return -1;
1571 }
1572
1573 if (restart_successful) {
1574 SLOGE("System already restarted with encrypted disk, aborting");
1575 return -1;
1576 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001577
Paul Lawrencef4faa572014-01-29 13:31:03 -08001578 if (restart_main) {
1579 /* Here is where we shut down the framework. The init scripts
1580 * start all services in one of three classes: core, main or late_start.
1581 * On boot, we start core and main. Now, we stop main, but not core,
1582 * as core includes vold and a few other really important things that
1583 * we need to keep running. Once main has stopped, we should be able
1584 * to umount the tmpfs /data, then mount the encrypted /data.
1585 * We then restart the class main, and also the class late_start.
1586 * At the moment, I've only put a few things in late_start that I know
1587 * are not needed to bring up the framework, and that also cause problems
1588 * with unmounting the tmpfs /data, but I hope to add add more services
1589 * to the late_start class as we optimize this to decrease the delay
1590 * till the user is asked for the password to the filesystem.
1591 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001592
Paul Lawrencef4faa572014-01-29 13:31:03 -08001593 /* The init files are setup to stop the class main when vold.decrypt is
1594 * set to trigger_reset_main.
1595 */
1596 property_set("vold.decrypt", "trigger_reset_main");
1597 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001598
Paul Lawrencef4faa572014-01-29 13:31:03 -08001599 /* Ugh, shutting down the framework is not synchronous, so until it
1600 * can be fixed, this horrible hack will wait a moment for it all to
1601 * shut down before proceeding. Without it, some devices cannot
1602 * restart the graphics services.
1603 */
1604 sleep(2);
1605 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001606
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001607 /* Now that the framework is shutdown, we should be able to umount()
1608 * the tmpfs filesystem, and mount the real one.
1609 */
1610
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001611 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1612 if (strlen(crypto_blkdev) == 0) {
1613 SLOGE("fs_crypto_blkdev not set\n");
1614 return -1;
1615 }
1616
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001617 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001618 /* If ro.crypto.readonly is set to 1, mount the decrypted
1619 * filesystem readonly. This is used when /data is mounted by
1620 * recovery mode.
1621 */
1622 char ro_prop[PROPERTY_VALUE_MAX];
1623 property_get("ro.crypto.readonly", ro_prop, "");
1624 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1625 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1626 rec->flags |= MS_RDONLY;
1627 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001628
Ken Sumralle5032c42012-04-01 23:58:44 -07001629 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001630 int retries = RETRY_MOUNT_ATTEMPTS;
1631 int mount_rc;
1632 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1633 crypto_blkdev, 0))
1634 != 0) {
1635 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1636 /* TODO: invoke something similar to
1637 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1638 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1639 SLOGI("Failed to mount %s because it is busy - waiting",
1640 crypto_blkdev);
1641 if (--retries) {
1642 sleep(RETRY_MOUNT_DELAY_SECONDS);
1643 } else {
1644 /* Let's hope that a reboot clears away whatever is keeping
1645 the mount busy */
1646 cryptfs_reboot(reboot);
1647 }
1648 } else {
1649 SLOGE("Failed to mount decrypted data");
1650 cryptfs_set_corrupt();
1651 cryptfs_trigger_restart_min_framework();
1652 SLOGI("Started framework to offer wipe");
1653 return -1;
1654 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001655 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001656
Ken Sumralle5032c42012-04-01 23:58:44 -07001657 property_set("vold.decrypt", "trigger_load_persist_props");
1658 /* Create necessary paths on /data */
1659 if (prep_data_fs()) {
1660 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001661 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001662
1663 /* startup service classes main and late_start */
1664 property_set("vold.decrypt", "trigger_restart_framework");
1665 SLOGD("Just triggered restart_framework\n");
1666
1667 /* Give it a few moments to get started */
1668 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001669 }
1670
Ken Sumrall0cc16632011-01-18 20:32:26 -08001671 if (rc == 0) {
1672 restart_successful = 1;
1673 }
1674
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001675 return rc;
1676}
1677
Paul Lawrencef4faa572014-01-29 13:31:03 -08001678int cryptfs_restart(void)
1679{
1680 /* Call internal implementation forcing a restart of main service group */
1681 return cryptfs_restart_internal(1);
1682}
1683
Mark Salyzyn3e971272014-01-21 13:27:04 -08001684static int do_crypto_complete(char *mount_point UNUSED)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001685{
1686 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001687 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001688 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001689
1690 property_get("ro.crypto.state", encrypted_state, "");
1691 if (strcmp(encrypted_state, "encrypted") ) {
1692 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001693 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001694 }
1695
Ken Sumrall160b4d62013-04-22 12:15:39 -07001696 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001697 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001698
Ken Sumralle1a45852011-12-14 21:24:27 -08001699 /*
1700 * Only report this error if key_loc is a file and it exists.
1701 * If the device was never encrypted, and /data is not mountable for
1702 * some reason, returning 1 should prevent the UI from presenting the
1703 * a "enter password" screen, or worse, a "press button to wipe the
1704 * device" screen.
1705 */
1706 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1707 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001708 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001709 } else {
1710 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001711 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001712 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001713 }
1714
Paul Lawrence74f29f12014-08-28 15:54:10 -07001715 // Test for possible error flags
1716 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1717 SLOGE("Encryption process is partway completed\n");
1718 return CRYPTO_COMPLETE_PARTIAL;
1719 }
1720
1721 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1722 SLOGE("Encryption process was interrupted but cannot continue\n");
1723 return CRYPTO_COMPLETE_INCONSISTENT;
1724 }
1725
1726 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1727 SLOGE("Encryption is successful but data is corrupt\n");
1728 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001729 }
1730
1731 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001732 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001733}
1734
Paul Lawrencef4faa572014-01-29 13:31:03 -08001735static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1736 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001737{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001738 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001739 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001740 char crypto_blkdev[MAXPATHLEN];
1741 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001742 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001743 unsigned int orig_failed_decrypt_count;
1744 int rc;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001745 kdf_func kdf;
1746 void *kdf_params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001747 int use_keymaster = 0;
1748 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001749 unsigned char* intermediate_key = 0;
1750 size_t intermediate_key_size = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001751
Paul Lawrencef4faa572014-01-29 13:31:03 -08001752 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1753 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001754
Paul Lawrencef4faa572014-01-29 13:31:03 -08001755 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001756 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1757 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001758 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001759 rc = -1;
1760 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001761 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001762 }
1763
Paul Lawrencef4faa572014-01-29 13:31:03 -08001764 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1765
Ajay Dudani87701e22014-09-17 21:02:52 -07001766#ifdef CONFIG_HW_DISK_ENCRYPTION
1767 if(!set_hw_device_encryption_key(passwd, (char*) crypt_ftr->crypto_type_name)) {
1768 SLOGE("Hardware encryption key does not match");
1769 }
1770#endif
1771
Paul Lawrence74f29f12014-08-28 15:54:10 -07001772 // Create crypto block device - all (non fatal) code paths
1773 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001774 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1775 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001776 SLOGE("Error creating decrypted block device\n");
1777 rc = -1;
1778 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001779 }
1780
Paul Lawrence74f29f12014-08-28 15:54:10 -07001781 /* Work out if the problem is the password or the data */
1782 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1783 scrypted_intermediate_key)];
1784 int N = 1 << crypt_ftr->N_factor;
1785 int r = 1 << crypt_ftr->r_factor;
1786 int p = 1 << crypt_ftr->p_factor;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001787
Paul Lawrence74f29f12014-08-28 15:54:10 -07001788 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1789 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1790 N, r, p, scrypted_intermediate_key,
1791 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001792
Paul Lawrence74f29f12014-08-28 15:54:10 -07001793 // Does the key match the crypto footer?
1794 if (rc == 0 && memcmp(scrypted_intermediate_key,
1795 crypt_ftr->scrypted_intermediate_key,
1796 sizeof(scrypted_intermediate_key)) == 0) {
1797 SLOGI("Password matches");
1798 rc = 0;
1799 } else {
1800 /* Try mounting the file system anyway, just in case the problem's with
1801 * the footer, not the key. */
1802 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1803 mkdir(tmp_mount_point, 0755);
1804 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1805 SLOGE("Error temp mounting decrypted block device\n");
1806 delete_crypto_blk_dev(label);
1807
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001808 rc = ++crypt_ftr->failed_decrypt_count;
1809 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001810 } else {
1811 /* Success! */
1812 SLOGI("Password did not match but decrypted drive mounted - continue");
1813 umount(tmp_mount_point);
1814 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001815 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001816 }
1817
1818 if (rc == 0) {
1819 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001820 if (orig_failed_decrypt_count != 0) {
1821 put_crypt_ftr_and_key(crypt_ftr);
1822 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001823
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001824 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001825 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001826 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001827
1828 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001829 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001830 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001831 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001832 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001833 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001834 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001835
Paul Lawrence74f29f12014-08-28 15:54:10 -07001836 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001837 use_keymaster = keymaster_check_compatibility();
1838 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001839 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001840 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1841 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1842 upgrade = 1;
1843 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001844 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001845 upgrade = 1;
1846 }
1847
1848 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001849 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1850 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001851 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001852 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001853 }
1854 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001855
1856 // Do not fail even if upgrade failed - machine is bootable
1857 // Note that if this code is ever hit, there is a *serious* problem
1858 // since KDFs should never fail. You *must* fix the kdf before
1859 // proceeding!
1860 if (rc) {
1861 SLOGW("Upgrade failed with error %d,"
1862 " but continuing with previous state",
1863 rc);
1864 rc = 0;
1865 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001866 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001867 }
1868
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001869 errout:
1870 if (intermediate_key) {
1871 memset(intermediate_key, 0, intermediate_key_size);
1872 free(intermediate_key);
1873 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001874 return rc;
1875}
1876
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001877/* Called by vold when it wants to undo the crypto mapping of a volume it
1878 * manages. This is usually in response to a factory reset, when we want
1879 * to undo the crypto mapping so the volume is formatted in the clear.
1880 */
1881int cryptfs_revert_volume(const char *label)
1882{
1883 return delete_crypto_blk_dev((char *)label);
1884}
1885
Ken Sumrall29d8da82011-05-18 17:20:07 -07001886/*
1887 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1888 * Setup a dm-crypt mapping, use the saved master key from
1889 * setting up the /data mapping, and return the new device path.
1890 */
1891int cryptfs_setup_volume(const char *label, int major, int minor,
1892 char *crypto_sys_path, unsigned int max_path,
1893 int *new_major, int *new_minor)
1894{
1895 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1896 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001897 struct stat statbuf;
1898 int nr_sec, fd;
1899
1900 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1901
Ken Sumrall160b4d62013-04-22 12:15:39 -07001902 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001903
1904 /* Update the fs_size field to be the size of the volume */
1905 fd = open(real_blkdev, O_RDONLY);
1906 nr_sec = get_blkdev_size(fd);
1907 close(fd);
1908 if (nr_sec == 0) {
1909 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1910 return -1;
1911 }
1912
1913 sd_crypt_ftr.fs_size = nr_sec;
1914 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1915 crypto_blkdev, label);
1916
JP Abgrall3334c6a2014-10-10 15:52:11 -07001917 if (stat(crypto_blkdev, &statbuf) < 0) {
1918 SLOGE("Error get stat for crypto_blkdev %s. err=%d(%s)\n",
1919 crypto_blkdev, errno, strerror(errno));
1920 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07001921 *new_major = MAJOR(statbuf.st_rdev);
1922 *new_minor = MINOR(statbuf.st_rdev);
1923
1924 /* Create path to sys entry for this block device */
1925 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1926
1927 return 0;
1928}
1929
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001930int cryptfs_crypto_complete(void)
1931{
1932 return do_crypto_complete("/data");
1933}
1934
Paul Lawrencef4faa572014-01-29 13:31:03 -08001935int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1936{
1937 char encrypted_state[PROPERTY_VALUE_MAX];
1938 property_get("ro.crypto.state", encrypted_state, "");
1939 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1940 SLOGE("encrypted fs already validated or not running with encryption,"
1941 " aborting");
1942 return -1;
1943 }
1944
1945 if (get_crypt_ftr_and_key(crypt_ftr)) {
1946 SLOGE("Error getting crypt footer and key");
1947 return -1;
1948 }
1949
1950 return 0;
1951}
1952
Paul Lawrencefc615042014-10-04 15:32:29 -07001953/*
1954 * TODO - transition patterns to new format in calling code
1955 * and remove this vile hack, and the use of hex in
1956 * the password passing code.
1957 *
1958 * Patterns are passed in zero based (i.e. the top left dot
1959 * is represented by zero, the top middle one etc), but we want
1960 * to store them '1' based.
1961 * This is to allow us to migrate the calling code to use this
1962 * convention. It also solves a nasty problem whereby scrypt ignores
1963 * trailing zeros, so patterns ending at the top left could be
1964 * truncated, and similarly, you could add the top left to any
1965 * pattern and still match.
1966 * adjust_passwd is a hack function that returns the alternate representation
1967 * if the password appears to be a pattern (hex numbers all less than 09)
1968 * If it succeeds we need to try both, and in particular try the alternate
1969 * first. If the original matches, then we need to update the footer
1970 * with the alternate.
1971 * All code that accepts passwords must adjust them first. Since
1972 * cryptfs_check_passwd is always the first function called after a migration
1973 * (and indeed on any boot) we only need to do the double try in this
1974 * function.
1975 */
1976char* adjust_passwd(const char* passwd)
1977{
1978 size_t index, length;
1979
1980 if (!passwd) {
1981 return 0;
1982 }
1983
1984 // Check even length. Hex encoded passwords are always
1985 // an even length, since each character encodes to two characters.
1986 length = strlen(passwd);
1987 if (length % 2) {
1988 SLOGW("Password not correctly hex encoded.");
1989 return 0;
1990 }
1991
1992 // Check password is old-style pattern - a collection of hex
1993 // encoded bytes less than 9 (00 through 08)
1994 for (index = 0; index < length; index +=2) {
1995 if (passwd[index] != '0'
1996 || passwd[index + 1] < '0' || passwd[index + 1] > '8') {
1997 return 0;
1998 }
1999 }
2000
2001 // Allocate room for adjusted passwd and null terminate
2002 char* adjusted = malloc(length + 1);
2003 adjusted[length] = 0;
2004
2005 // Add 0x31 ('1') to each character
2006 for (index = 0; index < length; index += 2) {
2007 // output is 31 through 39 so set first byte to three, second to src + 1
2008 adjusted[index] = '3';
2009 adjusted[index + 1] = passwd[index + 1] + 1;
2010 }
2011
2012 return adjusted;
2013}
2014
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002015int cryptfs_check_passwd(char *passwd)
2016{
Paul Lawrencef4faa572014-01-29 13:31:03 -08002017 struct crypt_mnt_ftr crypt_ftr;
2018 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002019
Paul Lawrencef4faa572014-01-29 13:31:03 -08002020 rc = check_unmounted_and_get_ftr(&crypt_ftr);
2021 if (rc)
2022 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002023
Paul Lawrencefc615042014-10-04 15:32:29 -07002024 char* adjusted_passwd = adjust_passwd(passwd);
2025 if (adjusted_passwd) {
2026 int failed_decrypt_count = crypt_ftr.failed_decrypt_count;
2027 rc = test_mount_encrypted_fs(&crypt_ftr, adjusted_passwd,
2028 DATA_MNT_POINT, "userdata");
2029
2030 // Maybe the original one still works?
2031 if (rc) {
2032 // Don't double count this failure
2033 crypt_ftr.failed_decrypt_count = failed_decrypt_count;
2034 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
2035 DATA_MNT_POINT, "userdata");
2036 if (!rc) {
2037 // cryptfs_changepw also adjusts so pass original
2038 // Note that adjust_passwd only recognises patterns
2039 // so we can safely use CRYPT_TYPE_PATTERN
2040 SLOGI("Updating pattern to new format");
2041 cryptfs_changepw(CRYPT_TYPE_PATTERN, passwd);
2042 }
2043 }
2044 free(adjusted_passwd);
2045 } else {
2046 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
2047 DATA_MNT_POINT, "userdata");
2048 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002049
2050 if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002051 cryptfs_clear_password();
2052 password = strdup(passwd);
2053 struct timespec now;
2054 clock_gettime(CLOCK_BOOTTIME, &now);
2055 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002056 }
2057
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002058 return rc;
2059}
2060
Ken Sumrall3ad90722011-10-04 20:38:29 -07002061int cryptfs_verify_passwd(char *passwd)
2062{
2063 struct crypt_mnt_ftr crypt_ftr;
2064 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002065 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002066 char encrypted_state[PROPERTY_VALUE_MAX];
2067 int rc;
2068
2069 property_get("ro.crypto.state", encrypted_state, "");
2070 if (strcmp(encrypted_state, "encrypted") ) {
2071 SLOGE("device not encrypted, aborting");
2072 return -2;
2073 }
2074
2075 if (!master_key_saved) {
2076 SLOGE("encrypted fs not yet mounted, aborting");
2077 return -1;
2078 }
2079
2080 if (!saved_mount_point) {
2081 SLOGE("encrypted fs failed to save mount point, aborting");
2082 return -1;
2083 }
2084
Ken Sumrall160b4d62013-04-22 12:15:39 -07002085 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002086 SLOGE("Error getting crypt footer and key\n");
2087 return -1;
2088 }
2089
2090 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2091 /* If the device has no password, then just say the password is valid */
2092 rc = 0;
2093 } else {
Paul Lawrencefc615042014-10-04 15:32:29 -07002094 char* adjusted_passwd = adjust_passwd(passwd);
2095 if (adjusted_passwd) {
2096 passwd = adjusted_passwd;
2097 }
2098
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002099 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002100 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2101 /* They match, the password is correct */
2102 rc = 0;
2103 } else {
2104 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2105 sleep(1);
2106 rc = 1;
2107 }
Paul Lawrencefc615042014-10-04 15:32:29 -07002108
2109 free(adjusted_passwd);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002110 }
2111
2112 return rc;
2113}
2114
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002115/* Initialize a crypt_mnt_ftr structure. The keysize is
2116 * defaulted to 16 bytes, and the filesystem size to 0.
2117 * Presumably, at a minimum, the caller will update the
2118 * filesystem size and crypto_type_name after calling this function.
2119 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002120static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002121{
Ken Sumrall160b4d62013-04-22 12:15:39 -07002122 off64_t off;
2123
2124 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002125 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002126 ftr->major_version = CURRENT_MAJOR_VERSION;
2127 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002128 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06002129 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002130
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002131 switch (keymaster_check_compatibility()) {
2132 case 1:
2133 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2134 break;
2135
2136 case 0:
2137 ftr->kdf_type = KDF_SCRYPT;
2138 break;
2139
2140 default:
2141 SLOGE("keymaster_check_compatibility failed");
2142 return -1;
2143 }
2144
Kenny Rootc4c70f12013-06-14 12:11:38 -07002145 get_device_scrypt_params(ftr);
2146
Ken Sumrall160b4d62013-04-22 12:15:39 -07002147 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2148 if (get_crypt_ftr_info(NULL, &off) == 0) {
2149 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
2150 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
2151 ftr->persist_data_size;
2152 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002153
2154 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002155}
2156
Ken Sumrall29d8da82011-05-18 17:20:07 -07002157static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002158{
Ken Sumralle550f782013-08-20 13:48:23 -07002159 const char *args[10];
2160 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
2161 int num_args;
2162 int status;
2163 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002164 int rc = -1;
2165
Ken Sumrall29d8da82011-05-18 17:20:07 -07002166 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07002167 args[0] = "/system/bin/make_ext4fs";
2168 args[1] = "-a";
2169 args[2] = "/data";
2170 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07002171 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07002172 args[4] = size_str;
2173 args[5] = crypto_blkdev;
2174 num_args = 6;
2175 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
2176 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07002177 } else if (type == F2FS_FS) {
2178 args[0] = "/system/bin/mkfs.f2fs";
2179 args[1] = "-t";
2180 args[2] = "-d1";
2181 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07002182 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07002183 args[4] = size_str;
2184 num_args = 5;
2185 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
2186 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002187 } else {
2188 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
2189 return -1;
2190 }
2191
Ken Sumralle550f782013-08-20 13:48:23 -07002192 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
2193
2194 if (tmp != 0) {
2195 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002196 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07002197 if (WIFEXITED(status)) {
2198 if (WEXITSTATUS(status)) {
2199 SLOGE("Error creating filesystem on %s, exit status %d ",
2200 crypto_blkdev, WEXITSTATUS(status));
2201 } else {
2202 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
2203 rc = 0;
2204 }
2205 } else {
2206 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
2207 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002208 }
2209
2210 return rc;
2211}
2212
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002213#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08002214#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
2215#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002216
2217/* aligned 32K writes tends to make flash happy.
2218 * SD card association recommends it.
2219 */
Ajay Dudani87701e22014-09-17 21:02:52 -07002220#ifndef CONFIG_HW_DISK_ENCRYPTION
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002221#define BLOCKS_AT_A_TIME 8
Ajay Dudani87701e22014-09-17 21:02:52 -07002222#else
2223#define BLOCKS_AT_A_TIME 1024
2224#endif
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002225
2226struct encryptGroupsData
2227{
2228 int realfd;
2229 int cryptofd;
2230 off64_t numblocks;
2231 off64_t one_pct, cur_pct, new_pct;
2232 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002233 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002234 char* real_blkdev, * crypto_blkdev;
2235 int count;
2236 off64_t offset;
2237 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08002238 off64_t last_written_sector;
2239 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002240 time_t time_started;
2241 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002242};
2243
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002244static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002245{
2246 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002247
2248 if (is_used) {
2249 data->used_blocks_already_done++;
2250 }
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002251 if (data->tot_used_blocks) {
2252 data->new_pct = data->used_blocks_already_done / data->one_pct;
2253 } else {
2254 data->new_pct = data->blocks_already_done / data->one_pct;
2255 }
2256
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002257 if (data->new_pct > data->cur_pct) {
2258 char buf[8];
2259 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07002260 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002261 property_set("vold.encrypt_progress", buf);
2262 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002263
2264 if (data->cur_pct >= 5) {
Paul Lawrence9c58a872014-09-30 09:12:51 -07002265 struct timespec time_now;
2266 if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
2267 SLOGW("Error getting time");
2268 } else {
2269 double elapsed_time = difftime(time_now.tv_sec, data->time_started);
2270 off64_t remaining_blocks = data->tot_used_blocks
2271 - data->used_blocks_already_done;
2272 int remaining_time = (int)(elapsed_time * remaining_blocks
2273 / data->used_blocks_already_done);
Paul Lawrence71577502014-08-13 14:55:55 -07002274
Paul Lawrence9c58a872014-09-30 09:12:51 -07002275 // Change time only if not yet set, lower, or a lot higher for
2276 // best user experience
2277 if (data->remaining_time == -1
2278 || remaining_time < data->remaining_time
2279 || remaining_time > data->remaining_time + 60) {
2280 char buf[8];
2281 snprintf(buf, sizeof(buf), "%d", remaining_time);
2282 property_set("vold.encrypt_time_remaining", buf);
2283 data->remaining_time = remaining_time;
2284 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002285 }
2286 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002287}
2288
Paul Lawrence3846be12014-09-22 11:33:54 -07002289static void log_progress(struct encryptGroupsData const* data, bool completed)
2290{
2291 // Precondition - if completed data = 0 else data != 0
2292
2293 // Track progress so we can skip logging blocks
2294 static off64_t offset = -1;
2295
2296 // Need to close existing 'Encrypting from' log?
2297 if (completed || (offset != -1 && data->offset != offset)) {
2298 SLOGI("Encrypted to sector %" PRId64,
2299 offset / info.block_size * CRYPT_SECTOR_SIZE);
2300 offset = -1;
2301 }
2302
2303 // Need to start new 'Encrypting from' log?
2304 if (!completed && offset != data->offset) {
2305 SLOGI("Encrypting from sector %" PRId64,
2306 data->offset / info.block_size * CRYPT_SECTOR_SIZE);
2307 }
2308
2309 // Update offset
2310 if (!completed) {
2311 offset = data->offset + (off64_t)data->count * info.block_size;
2312 }
2313}
2314
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002315static int flush_outstanding_data(struct encryptGroupsData* data)
2316{
2317 if (data->count == 0) {
2318 return 0;
2319 }
2320
Elliott Hughes231bdba2014-06-25 18:36:19 -07002321 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002322
2323 if (pread64(data->realfd, data->buffer,
2324 info.block_size * data->count, data->offset)
2325 <= 0) {
2326 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2327 data->real_blkdev);
2328 return -1;
2329 }
2330
2331 if (pwrite64(data->cryptofd, data->buffer,
2332 info.block_size * data->count, data->offset)
2333 <= 0) {
2334 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2335 data->crypto_blkdev);
2336 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002337 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002338 log_progress(data, false);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002339 }
2340
2341 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002342 data->last_written_sector = (data->offset + data->count)
2343 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002344 return 0;
2345}
2346
2347static int encrypt_groups(struct encryptGroupsData* data)
2348{
2349 unsigned int i;
2350 u8 *block_bitmap = 0;
2351 unsigned int block;
2352 off64_t ret;
2353 int rc = -1;
2354
2355 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
2356 if (!data->buffer) {
2357 SLOGE("Failed to allocate crypto buffer");
2358 goto errout;
2359 }
2360
2361 block_bitmap = malloc(info.block_size);
2362 if (!block_bitmap) {
2363 SLOGE("failed to allocate block bitmap");
2364 goto errout;
2365 }
2366
2367 for (i = 0; i < aux_info.groups; ++i) {
2368 SLOGI("Encrypting group %d", i);
2369
2370 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2371 u32 block_count = min(info.blocks_per_group,
2372 aux_info.len_blocks - first_block);
2373
2374 off64_t offset = (u64)info.block_size
2375 * aux_info.bg_desc[i].bg_block_bitmap;
2376
2377 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2378 if (ret != (int)info.block_size) {
2379 SLOGE("failed to read all of block group bitmap %d", i);
2380 goto errout;
2381 }
2382
2383 offset = (u64)info.block_size * first_block;
2384
2385 data->count = 0;
2386
2387 for (block = 0; block < block_count; block++) {
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002388 int used = bitmap_get_bit(block_bitmap, block);
2389 update_progress(data, used);
2390 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002391 if (data->count == 0) {
2392 data->offset = offset;
2393 }
2394 data->count++;
2395 } else {
2396 if (flush_outstanding_data(data)) {
2397 goto errout;
2398 }
2399 }
2400
2401 offset += info.block_size;
2402
2403 /* Write data if we are aligned or buffer size reached */
2404 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2405 || data->count == BLOCKS_AT_A_TIME) {
2406 if (flush_outstanding_data(data)) {
2407 goto errout;
2408 }
2409 }
Paul Lawrence87999172014-02-20 12:21:31 -08002410
Paul Lawrence73d7a022014-06-09 14:10:09 -07002411 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002412 SLOGE("Stopping encryption due to low battery");
2413 rc = 0;
2414 goto errout;
2415 }
2416
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002417 }
2418 if (flush_outstanding_data(data)) {
2419 goto errout;
2420 }
2421 }
2422
Paul Lawrence87999172014-02-20 12:21:31 -08002423 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002424 rc = 0;
2425
2426errout:
Paul Lawrence3846be12014-09-22 11:33:54 -07002427 log_progress(0, true);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002428 free(data->buffer);
2429 free(block_bitmap);
2430 return rc;
2431}
2432
2433static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2434 char *real_blkdev,
2435 off64_t size,
2436 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002437 off64_t tot_size,
2438 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002439{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002440 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002441 struct encryptGroupsData data;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002442 int rc; // Can't initialize without causing warning -Wclobbered
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002443
Paul Lawrence87999172014-02-20 12:21:31 -08002444 if (previously_encrypted_upto > *size_already_done) {
2445 SLOGD("Not fast encrypting since resuming part way through");
2446 return -1;
2447 }
2448
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002449 memset(&data, 0, sizeof(data));
2450 data.real_blkdev = real_blkdev;
2451 data.crypto_blkdev = crypto_blkdev;
2452
2453 if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002454 SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
2455 real_blkdev, errno, strerror(errno));
Paul Lawrence74f29f12014-08-28 15:54:10 -07002456 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002457 goto errout;
2458 }
2459
2460 if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002461 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
JP Abgrall3334c6a2014-10-10 15:52:11 -07002462 crypto_blkdev, errno, strerror(errno));
JP Abgrall7fc1de82014-10-10 18:43:41 -07002463 rc = ENABLE_INPLACE_ERR_DEV;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002464 goto errout;
2465 }
2466
2467 if (setjmp(setjmp_env)) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002468 SLOGE("Reading ext4 extent caused an exception\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002469 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002470 goto errout;
2471 }
2472
2473 if (read_ext(data.realfd, 0) != 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002474 SLOGE("Failed to read ext4 extent\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002475 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002476 goto errout;
2477 }
2478
2479 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2480 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2481 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2482
JP Abgrall7fc1de82014-10-10 18:43:41 -07002483 SLOGI("Encrypting ext4 filesystem in place...");
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002484
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002485 data.tot_used_blocks = data.numblocks;
2486 for (i = 0; i < aux_info.groups; ++i) {
2487 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2488 }
2489
2490 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002491 data.cur_pct = 0;
Paul Lawrence9c58a872014-09-30 09:12:51 -07002492
2493 struct timespec time_started = {0};
2494 if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
2495 SLOGW("Error getting time at start");
2496 // Note - continue anyway - we'll run with 0
2497 }
2498 data.time_started = time_started.tv_sec;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002499 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002500
2501 rc = encrypt_groups(&data);
2502 if (rc) {
2503 SLOGE("Error encrypting groups");
2504 goto errout;
2505 }
2506
Paul Lawrence87999172014-02-20 12:21:31 -08002507 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002508 rc = 0;
2509
2510errout:
2511 close(data.realfd);
2512 close(data.cryptofd);
2513
2514 return rc;
2515}
2516
Paul Lawrence3846be12014-09-22 11:33:54 -07002517static void log_progress_f2fs(u64 block, bool completed)
2518{
2519 // Precondition - if completed data = 0 else data != 0
2520
2521 // Track progress so we can skip logging blocks
2522 static u64 last_block = (u64)-1;
2523
2524 // Need to close existing 'Encrypting from' log?
2525 if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
2526 SLOGI("Encrypted to block %" PRId64, last_block);
2527 last_block = -1;
2528 }
2529
2530 // Need to start new 'Encrypting from' log?
2531 if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
2532 SLOGI("Encrypting from block %" PRId64, block);
2533 }
2534
2535 // Update offset
2536 if (!completed) {
2537 last_block = block;
2538 }
2539}
2540
Daniel Rosenberge82df162014-08-15 22:19:23 +00002541static int encrypt_one_block_f2fs(u64 pos, void *data)
2542{
2543 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2544
2545 priv_dat->blocks_already_done = pos - 1;
2546 update_progress(priv_dat, 1);
2547
2548 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2549
2550 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002551 SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002552 return -1;
2553 }
2554
2555 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002556 SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002557 return -1;
2558 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002559 log_progress_f2fs(pos, false);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002560 }
2561
2562 return 0;
2563}
2564
2565static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2566 char *real_blkdev,
2567 off64_t size,
2568 off64_t *size_already_done,
2569 off64_t tot_size,
2570 off64_t previously_encrypted_upto)
2571{
2572 u32 i;
2573 struct encryptGroupsData data;
2574 struct f2fs_info *f2fs_info = NULL;
JP Abgrall7fc1de82014-10-10 18:43:41 -07002575 int rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002576 if (previously_encrypted_upto > *size_already_done) {
2577 SLOGD("Not fast encrypting since resuming part way through");
JP Abgrall7fc1de82014-10-10 18:43:41 -07002578 return ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002579 }
2580 memset(&data, 0, sizeof(data));
2581 data.real_blkdev = real_blkdev;
2582 data.crypto_blkdev = crypto_blkdev;
2583 data.realfd = -1;
2584 data.cryptofd = -1;
2585 if ( (data.realfd = open64(real_blkdev, O_RDWR)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002586 SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
Daniel Rosenberge82df162014-08-15 22:19:23 +00002587 real_blkdev);
2588 goto errout;
2589 }
2590 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002591 SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
JP Abgrall3334c6a2014-10-10 15:52:11 -07002592 crypto_blkdev, errno, strerror(errno));
JP Abgrall7fc1de82014-10-10 18:43:41 -07002593 rc = ENABLE_INPLACE_ERR_DEV;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002594 goto errout;
2595 }
2596
2597 f2fs_info = generate_f2fs_info(data.realfd);
2598 if (!f2fs_info)
2599 goto errout;
2600
2601 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2602 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2603 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2604
2605 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2606
2607 data.one_pct = data.tot_used_blocks / 100;
2608 data.cur_pct = 0;
2609 data.time_started = time(NULL);
2610 data.remaining_time = -1;
2611
2612 data.buffer = malloc(f2fs_info->block_size);
2613 if (!data.buffer) {
2614 SLOGE("Failed to allocate crypto buffer");
2615 goto errout;
2616 }
2617
2618 data.count = 0;
2619
2620 /* Currently, this either runs to completion, or hits a nonrecoverable error */
2621 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2622
2623 if (rc) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002624 SLOGE("Error in running over f2fs blocks");
2625 rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002626 goto errout;
2627 }
2628
2629 *size_already_done += size;
2630 rc = 0;
2631
2632errout:
2633 if (rc)
2634 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2635
Paul Lawrence3846be12014-09-22 11:33:54 -07002636 log_progress_f2fs(0, true);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002637 free(f2fs_info);
2638 free(data.buffer);
2639 close(data.realfd);
2640 close(data.cryptofd);
2641
2642 return rc;
2643}
2644
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002645static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2646 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002647 off64_t tot_size,
2648 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002649{
2650 int realfd, cryptofd;
2651 char *buf[CRYPT_INPLACE_BUFSIZE];
JP Abgrall7fc1de82014-10-10 18:43:41 -07002652 int rc = ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002653 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002654 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002655 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002656
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002657 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
2658 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002659 return ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002660 }
2661
2662 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002663 SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
2664 crypto_blkdev, errno, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002665 close(realfd);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002666 return ENABLE_INPLACE_ERR_DEV;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002667 }
2668
2669 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2670 * The size passed in is the number of 512 byte sectors in the filesystem.
2671 * So compute the number of whole 4K blocks we should read/write,
2672 * and the remainder.
2673 */
2674 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2675 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002676 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2677 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002678
2679 SLOGE("Encrypting filesystem in place...");
2680
Paul Lawrence87999172014-02-20 12:21:31 -08002681 i = previously_encrypted_upto + 1 - *size_already_done;
2682
2683 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2684 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2685 goto errout;
2686 }
2687
2688 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2689 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2690 goto errout;
2691 }
2692
2693 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2694 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2695 SLOGE("Error reading initial sectors from real_blkdev %s for "
2696 "inplace encrypt\n", crypto_blkdev);
2697 goto errout;
2698 }
2699 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2700 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2701 "inplace encrypt\n", crypto_blkdev);
2702 goto errout;
2703 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002704 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002705 }
2706 }
2707
Ken Sumrall29d8da82011-05-18 17:20:07 -07002708 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002709 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002710 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002711 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002712 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002713 if (new_pct > cur_pct) {
2714 char buf[8];
2715
2716 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002717 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002718 property_set("vold.encrypt_progress", buf);
2719 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002720 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002721 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002722 goto errout;
2723 }
2724 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002725 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2726 goto errout;
2727 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002728 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002729 CRYPT_SECTORS_PER_BUFSIZE,
2730 i * CRYPT_SECTORS_PER_BUFSIZE);
2731 }
2732
Paul Lawrence73d7a022014-06-09 14:10:09 -07002733 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002734 SLOGE("Stopping encryption due to low battery");
2735 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2736 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002737 goto errout;
2738 }
2739 }
2740
2741 /* Do any remaining sectors */
2742 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002743 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2744 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002745 goto errout;
2746 }
Paul Lawrence87999172014-02-20 12:21:31 -08002747 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2748 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002749 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002750 } else {
2751 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002752 }
2753 }
2754
Ken Sumrall29d8da82011-05-18 17:20:07 -07002755 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002756 rc = 0;
2757
2758errout:
2759 close(realfd);
2760 close(cryptofd);
2761
2762 return rc;
2763}
2764
JP Abgrall7fc1de82014-10-10 18:43:41 -07002765/* returns on of the ENABLE_INPLACE_* return codes */
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002766static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2767 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002768 off64_t tot_size,
2769 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002770{
JP Abgrall7fc1de82014-10-10 18:43:41 -07002771 int rc_ext4, rc_f2fs, rc_full;
Paul Lawrence87999172014-02-20 12:21:31 -08002772 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002773 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002774 }
2775
2776 if (*size_already_done + size < previously_encrypted_upto) {
2777 *size_already_done += size;
2778 return 0;
2779 }
2780
Daniel Rosenberge82df162014-08-15 22:19:23 +00002781 /* TODO: identify filesystem type.
2782 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2783 * then we will drop down to cryptfs_enable_inplace_f2fs.
2784 * */
JP Abgrall7fc1de82014-10-10 18:43:41 -07002785 if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002786 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002787 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002788 return 0;
2789 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002790 SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002791
JP Abgrall7fc1de82014-10-10 18:43:41 -07002792 if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002793 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002794 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002795 return 0;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002796 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002797 SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002798
JP Abgrall7fc1de82014-10-10 18:43:41 -07002799 rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002800 size, size_already_done, tot_size,
2801 previously_encrypted_upto);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002802 SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
2803
2804 /* Hack for b/17898962, the following is the symptom... */
2805 if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
2806 && rc_f2fs == ENABLE_INPLACE_ERR_DEV
2807 && rc_full == ENABLE_INPLACE_ERR_DEV) {
2808 return ENABLE_INPLACE_ERR_DEV;
2809 }
2810 return rc_full;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002811}
2812
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002813#define CRYPTO_ENABLE_WIPE 1
2814#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002815
2816#define FRAMEWORK_BOOT_WAIT 60
2817
Ken Sumrall29d8da82011-05-18 17:20:07 -07002818static inline int should_encrypt(struct volume_info *volume)
2819{
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002820 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
Ken Sumrall29d8da82011-05-18 17:20:07 -07002821 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
2822}
2823
Paul Lawrence87999172014-02-20 12:21:31 -08002824static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2825{
2826 int fd = open(filename, O_RDONLY);
2827 if (fd == -1) {
2828 SLOGE("Error opening file %s", filename);
2829 return -1;
2830 }
2831
2832 char block[CRYPT_INPLACE_BUFSIZE];
2833 memset(block, 0, sizeof(block));
2834 if (unix_read(fd, block, sizeof(block)) < 0) {
2835 SLOGE("Error reading file %s", filename);
2836 close(fd);
2837 return -1;
2838 }
2839
2840 close(fd);
2841
2842 SHA256_CTX c;
2843 SHA256_Init(&c);
2844 SHA256_Update(&c, block, sizeof(block));
2845 SHA256_Final(buf, &c);
2846
2847 return 0;
2848}
2849
JP Abgrall62c7af32014-06-16 13:01:23 -07002850static int get_fs_type(struct fstab_rec *rec)
2851{
2852 if (!strcmp(rec->fs_type, "ext4")) {
2853 return EXT4_FS;
2854 } else if (!strcmp(rec->fs_type, "f2fs")) {
2855 return F2FS_FS;
2856 } else {
2857 return -1;
2858 }
2859}
2860
Paul Lawrence87999172014-02-20 12:21:31 -08002861static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2862 char *crypto_blkdev, char *real_blkdev,
2863 int previously_encrypted_upto)
2864{
2865 off64_t cur_encryption_done=0, tot_encryption_size=0;
2866 int i, rc = -1;
2867
Paul Lawrence73d7a022014-06-09 14:10:09 -07002868 if (!is_battery_ok_to_start()) {
2869 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002870 return 0;
2871 }
2872
2873 /* The size of the userdata partition, and add in the vold volumes below */
2874 tot_encryption_size = crypt_ftr->fs_size;
2875
2876 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002877 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2878 int fs_type = get_fs_type(rec);
2879 if (fs_type < 0) {
2880 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2881 return -1;
2882 }
2883 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002884 } else if (how == CRYPTO_ENABLE_INPLACE) {
2885 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2886 crypt_ftr->fs_size, &cur_encryption_done,
2887 tot_encryption_size,
2888 previously_encrypted_upto);
2889
JP Abgrall7fc1de82014-10-10 18:43:41 -07002890 if (rc == ENABLE_INPLACE_ERR_DEV) {
2891 /* Hack for b/17898962 */
2892 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2893 cryptfs_reboot(reboot);
2894 }
2895
Paul Lawrence73d7a022014-06-09 14:10:09 -07002896 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002897 crypt_ftr->encrypted_upto = cur_encryption_done;
2898 }
2899
Paul Lawrence73d7a022014-06-09 14:10:09 -07002900 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002901 /* The inplace routine never actually sets the progress to 100% due
2902 * to the round down nature of integer division, so set it here */
2903 property_set("vold.encrypt_progress", "100");
2904 }
2905 } else {
2906 /* Shouldn't happen */
2907 SLOGE("cryptfs_enable: internal error, unknown option\n");
2908 rc = -1;
2909 }
2910
2911 return rc;
2912}
2913
Paul Lawrence13486032014-02-03 13:28:11 -08002914int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
2915 int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002916{
2917 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002918 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07002919 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002920 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07002921 int rc=-1, fd, i, ret;
Paul Lawrence87999172014-02-20 12:21:31 -08002922 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002923 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002924 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002925 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002926 char key_loc[PROPERTY_VALUE_MAX];
2927 char fuse_sdcard[PROPERTY_VALUE_MAX];
2928 char *sd_mnt_point;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002929 int num_vols;
2930 struct volume_info *vol_list = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002931 off64_t previously_encrypted_upto = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002932
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002933 if (!strcmp(howarg, "wipe")) {
2934 how = CRYPTO_ENABLE_WIPE;
2935 } else if (! strcmp(howarg, "inplace")) {
2936 how = CRYPTO_ENABLE_INPLACE;
2937 } else {
2938 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002939 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002940 }
2941
Paul Lawrence87999172014-02-20 12:21:31 -08002942 /* See if an encryption was underway and interrupted */
2943 if (how == CRYPTO_ENABLE_INPLACE
2944 && get_crypt_ftr_and_key(&crypt_ftr) == 0
2945 && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
2946 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2947 crypt_ftr.encrypted_upto = 0;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002948 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
2949
2950 /* At this point, we are in an inconsistent state. Until we successfully
2951 complete encryption, a reboot will leave us broken. So mark the
2952 encryption failed in case that happens.
2953 On successfully completing encryption, remove this flag */
2954 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2955
2956 put_crypt_ftr_and_key(&crypt_ftr);
Paul Lawrence87999172014-02-20 12:21:31 -08002957 }
2958
2959 property_get("ro.crypto.state", encrypted_state, "");
2960 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2961 SLOGE("Device is already running encrypted, aborting");
2962 goto error_unencrypted;
2963 }
2964
2965 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2966 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002967 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002968
Ken Sumrall3ed82362011-01-28 23:31:16 -08002969 /* Get the size of the real block device */
2970 fd = open(real_blkdev, O_RDONLY);
2971 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
2972 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2973 goto error_unencrypted;
2974 }
2975 close(fd);
2976
2977 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002978 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002979 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002980 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002981 if (fs_size_sec == 0)
2982 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2983
Paul Lawrence87999172014-02-20 12:21:31 -08002984 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002985
2986 if (fs_size_sec > max_fs_size_sec) {
2987 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2988 goto error_unencrypted;
2989 }
2990 }
2991
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002992 /* Get a wakelock as this may take a while, and we don't want the
2993 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2994 * wants to keep the screen on, it can grab a full wakelock.
2995 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002996 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002997 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2998
Jeff Sharkey7382f812012-08-23 14:08:59 -07002999 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07003000 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07003001 if (!sd_mnt_point) {
3002 sd_mnt_point = getenv("EXTERNAL_STORAGE");
3003 }
3004 if (!sd_mnt_point) {
3005 sd_mnt_point = "/mnt/sdcard";
3006 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07003007
Paul Lawrence87999172014-02-20 12:21:31 -08003008 /* TODO
3009 * Currently do not have test devices with multiple encryptable volumes.
3010 * When we acquire some, re-add support.
3011 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003012 num_vols=vold_getNumDirectVolumes();
3013 vol_list = malloc(sizeof(struct volume_info) * num_vols);
3014 vold_getDirectVolumeList(vol_list);
3015
3016 for (i=0; i<num_vols; i++) {
3017 if (should_encrypt(&vol_list[i])) {
Paul Lawrence87999172014-02-20 12:21:31 -08003018 SLOGE("Cannot encrypt if there are multiple encryptable volumes"
3019 "%s\n", vol_list[i].label);
3020 goto error_unencrypted;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003021 }
3022 }
3023
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003024 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003025 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003026 */
3027 property_set("vold.decrypt", "trigger_shutdown_framework");
3028 SLOGD("Just asked init to shut down class main\n");
3029
Ken Sumrall425524d2012-06-14 20:55:28 -07003030 if (vold_unmountAllAsecs()) {
3031 /* Just report the error. If any are left mounted,
3032 * umounting /data below will fail and handle the error.
3033 */
3034 SLOGE("Error unmounting internal asecs");
3035 }
3036
Ken Sumrall29d8da82011-05-18 17:20:07 -07003037 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
3038 if (!strcmp(fuse_sdcard, "true")) {
3039 /* This is a device using the fuse layer to emulate the sdcard semantics
3040 * on top of the userdata partition. vold does not manage it, it is managed
3041 * by the sdcard service. The sdcard service was killed by the property trigger
3042 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
3043 * unlike the case for vold managed devices above.
3044 */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07003045 if (wait_and_unmount(sd_mnt_point, false)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07003046 goto error_shutting_down;
3047 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08003048 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003049
3050 /* Now unmount the /data partition. */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07003051 if (wait_and_unmount(DATA_MNT_POINT, false)) {
JP Abgrall502dc742013-11-01 13:06:20 -07003052 if (allow_reboot) {
3053 goto error_shutting_down;
3054 } else {
3055 goto error_unencrypted;
3056 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003057 }
3058
3059 /* Do extra work for a better UX when doing the long inplace encryption */
3060 if (how == CRYPTO_ENABLE_INPLACE) {
3061 /* Now that /data is unmounted, we need to mount a tmpfs
3062 * /data, set a property saying we're doing inplace encryption,
3063 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003064 */
Ken Sumralle5032c42012-04-01 23:58:44 -07003065 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003066 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003067 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003068 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08003069 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003070
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003071 /* restart the framework. */
3072 /* Create necessary paths on /data */
3073 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003074 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003075 }
3076
Ken Sumrall92736ef2012-10-17 20:57:14 -07003077 /* Ugh, shutting down the framework is not synchronous, so until it
3078 * can be fixed, this horrible hack will wait a moment for it all to
3079 * shut down before proceeding. Without it, some devices cannot
3080 * restart the graphics services.
3081 */
3082 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003083 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003084
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003085 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003086 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence87999172014-02-20 12:21:31 -08003087 if (previously_encrypted_upto == 0) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07003088 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
3089 goto error_shutting_down;
3090 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003091
Paul Lawrence87999172014-02-20 12:21:31 -08003092 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
3093 crypt_ftr.fs_size = nr_sec
3094 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
3095 } else {
3096 crypt_ftr.fs_size = nr_sec;
3097 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07003098 /* At this point, we are in an inconsistent state. Until we successfully
3099 complete encryption, a reboot will leave us broken. So mark the
3100 encryption failed in case that happens.
3101 On successfully completing encryption, remove this flag */
3102 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence87999172014-02-20 12:21:31 -08003103 crypt_ftr.crypt_type = crypt_type;
Ajay Dudani87701e22014-09-17 21:02:52 -07003104#ifndef CONFIG_HW_DISK_ENCRYPTION
3105 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
3106#else
3107 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-xts", MAX_CRYPTO_TYPE_NAME_LEN);
3108
3109 rc = clear_hw_device_encryption_key();
3110 if (!rc) {
3111 SLOGE("Error clearing device encryption hardware key. rc = %d", rc);
3112 }
3113
3114 rc = set_hw_device_encryption_key(passwd,
3115 (char*) crypt_ftr.crypto_type_name);
3116 if (!rc) {
3117 SLOGE("Error initializing device encryption hardware key. rc = %d", rc);
3118 goto error_shutting_down;
3119 }
3120#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003121
Paul Lawrence87999172014-02-20 12:21:31 -08003122 /* Make an encrypted master key */
3123 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
3124 SLOGE("Cannot create encrypted master key\n");
3125 goto error_shutting_down;
3126 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003127
Paul Lawrence87999172014-02-20 12:21:31 -08003128 /* Write the key to the end of the partition */
3129 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003130
Paul Lawrence87999172014-02-20 12:21:31 -08003131 /* If any persistent data has been remembered, save it.
3132 * If none, create a valid empty table and save that.
3133 */
3134 if (!persist_data) {
3135 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
3136 if (pdata) {
3137 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
3138 persist_data = pdata;
3139 }
3140 }
3141 if (persist_data) {
3142 save_persistent_data();
3143 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003144 }
3145
Ajay Dudani87701e22014-09-17 21:02:52 -07003146 if (how == CRYPTO_ENABLE_INPLACE) {
3147 /* startup service classes main and late_start */
3148 property_set("vold.decrypt", "trigger_restart_min_framework");
3149 SLOGD("Just triggered restart_min_framework\n");
3150
3151 /* OK, the framework is restarted and will soon be showing a
3152 * progress bar. Time to setup an encrypted mapping, and
3153 * either write a new filesystem, or encrypt in place updating
3154 * the progress bar as we work.
3155 */
3156 }
3157
Paul Lawrenced0c7b172014-08-08 14:28:10 -07003158 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07003159 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
3160 "userdata");
3161
Paul Lawrence87999172014-02-20 12:21:31 -08003162 /* If we are continuing, check checksums match */
3163 rc = 0;
3164 if (previously_encrypted_upto) {
3165 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
3166 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07003167
Paul Lawrence87999172014-02-20 12:21:31 -08003168 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
3169 sizeof(hash_first_block)) != 0) {
3170 SLOGE("Checksums do not match - trigger wipe");
3171 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003172 }
3173 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003174
Paul Lawrence87999172014-02-20 12:21:31 -08003175 if (!rc) {
3176 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
3177 crypto_blkdev, real_blkdev,
3178 previously_encrypted_upto);
3179 }
3180
3181 /* Calculate checksum if we are not finished */
Paul Lawrence73d7a022014-06-09 14:10:09 -07003182 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003183 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
3184 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07003185 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08003186 SLOGE("Error calculating checksum for continuing encryption");
3187 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003188 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003189 }
3190
3191 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003192 delete_crypto_blk_dev("userdata");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003193
3194 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003195
3196 if (! rc) {
3197 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003198 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08003199
Paul Lawrence6bfed202014-07-28 12:47:22 -07003200 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003201 SLOGD("Encrypted up to sector %lld - will continue after reboot",
3202 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07003203 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08003204 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07003205
Paul Lawrence6bfed202014-07-28 12:47:22 -07003206 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08003207
Paul Lawrence73d7a022014-06-09 14:10:09 -07003208 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003209 char value[PROPERTY_VALUE_MAX];
3210 property_get("ro.crypto.state", value, "");
3211 if (!strcmp(value, "")) {
3212 /* default encryption - continue first boot sequence */
3213 property_set("ro.crypto.state", "encrypted");
3214 release_wake_lock(lockid);
3215 cryptfs_check_passwd(DEFAULT_PASSWORD);
3216 cryptfs_restart_internal(1);
3217 return 0;
3218 } else {
3219 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08003220 cryptfs_reboot(reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003221 }
Paul Lawrence87999172014-02-20 12:21:31 -08003222 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003223 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Paul Lawrence87999172014-02-20 12:21:31 -08003224 cryptfs_reboot(shutdown);
3225 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003226 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003227 char value[PROPERTY_VALUE_MAX];
3228
Ken Sumrall319369a2012-06-27 16:30:18 -07003229 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003230 if (!strcmp(value, "1")) {
3231 /* wipe data if encryption failed */
3232 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
3233 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07003234 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003235 if (fd >= 0) {
Jeff Sharkeydd1a8042014-09-24 11:46:51 -07003236 write(fd, "--wipe_data\n", strlen("--wipe_data\n") + 1);
3237 write(fd, "--reason=cryptfs_enable_internal\n", strlen("--reason=cryptfs_enable_internal\n") + 1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003238 close(fd);
3239 } else {
3240 SLOGE("could not open /cache/recovery/command\n");
3241 }
Paul Lawrence87999172014-02-20 12:21:31 -08003242 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003243 } else {
3244 /* set property to trigger dialog */
3245 property_set("vold.encrypt_progress", "error_partially_encrypted");
3246 release_wake_lock(lockid);
3247 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003248 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003249 }
3250
Ken Sumrall3ed82362011-01-28 23:31:16 -08003251 /* hrm, the encrypt step claims success, but the reboot failed.
3252 * This should not happen.
3253 * Set the property and return. Hope the framework can deal with it.
3254 */
3255 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003256 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003257 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08003258
3259error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07003260 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003261 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003262 if (lockid[0]) {
3263 release_wake_lock(lockid);
3264 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003265 return -1;
3266
3267error_shutting_down:
3268 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3269 * but the framework is stopped and not restarted to show the error, so it's up to
3270 * vold to restart the system.
3271 */
3272 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08003273 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003274
3275 /* shouldn't get here */
3276 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003277 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003278 if (lockid[0]) {
3279 release_wake_lock(lockid);
3280 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003281 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003282}
3283
Paul Lawrence45f10532014-04-04 18:11:56 +00003284int cryptfs_enable(char *howarg, int type, char *passwd, int allow_reboot)
Paul Lawrence13486032014-02-03 13:28:11 -08003285{
Paul Lawrencefc615042014-10-04 15:32:29 -07003286 char* adjusted_passwd = adjust_passwd(passwd);
3287 if (adjusted_passwd) {
3288 passwd = adjusted_passwd;
3289 }
3290
3291 int rc = cryptfs_enable_internal(howarg, type, passwd, allow_reboot);
3292
3293 free(adjusted_passwd);
3294 return rc;
Paul Lawrence13486032014-02-03 13:28:11 -08003295}
3296
3297int cryptfs_enable_default(char *howarg, int allow_reboot)
3298{
3299 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
3300 DEFAULT_PASSWORD, allow_reboot);
3301}
3302
3303int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003304{
3305 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003306 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003307
3308 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003309 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003310 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003311 return -1;
3312 }
3313
Paul Lawrencef4faa572014-01-29 13:31:03 -08003314 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3315 SLOGE("Invalid crypt_type %d", crypt_type);
3316 return -1;
3317 }
3318
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003319 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003320 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003321 SLOGE("Error getting crypt footer and key");
3322 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003323 }
3324
Paul Lawrencef4faa572014-01-29 13:31:03 -08003325 crypt_ftr.crypt_type = crypt_type;
3326
Paul Lawrencefc615042014-10-04 15:32:29 -07003327 char* adjusted_passwd = adjust_passwd(newpw);
3328 if (adjusted_passwd) {
3329 newpw = adjusted_passwd;
3330 }
3331
Paul Lawrencef4faa572014-01-29 13:31:03 -08003332 encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
3333 : newpw,
3334 crypt_ftr.salt,
3335 saved_master_key,
3336 crypt_ftr.master_key,
3337 &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003338
Jason parks70a4b3f2011-01-28 10:10:47 -06003339 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003340 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003341
Paul Lawrencefc615042014-10-04 15:32:29 -07003342 free(adjusted_passwd);
Ajay Dudani87701e22014-09-17 21:02:52 -07003343
3344#ifdef CONFIG_HW_DISK_ENCRYPTION
3345 if (crypt_type == CRYPT_TYPE_DEFAULT) {
3346 int rc = update_hw_device_encryption_key(DEFAULT_PASSWORD, (char*) crypt_ftr.crypto_type_name);
3347 SLOGD("Update hardware encryption key to default for crypt_type: %d. rc = %d", crypt_type, rc);
3348 if (!rc)
3349 return -1;
3350 } else {
3351 int rc = update_hw_device_encryption_key(newpw, (char*) crypt_ftr.crypto_type_name);
3352 SLOGD("Update hardware encryption key for crypt_type: %d. rc = %d", crypt_type, rc);
3353 if (!rc)
3354 return -1;
3355 }
3356#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003357 return 0;
3358}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003359
Rubin Xu85c01f92014-10-13 12:49:54 +01003360static unsigned int persist_get_max_entries(int encrypted) {
3361 struct crypt_mnt_ftr crypt_ftr;
3362 unsigned int dsize;
3363 unsigned int max_persistent_entries;
3364
3365 /* If encrypted, use the values from the crypt_ftr, otherwise
3366 * use the values for the current spec.
3367 */
3368 if (encrypted) {
3369 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3370 return -1;
3371 }
3372 dsize = crypt_ftr.persist_data_size;
3373 } else {
3374 dsize = CRYPT_PERSIST_DATA_SIZE;
3375 }
3376
3377 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3378 sizeof(struct crypt_persist_entry);
3379
3380 return max_persistent_entries;
3381}
3382
3383static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003384{
3385 unsigned int i;
3386
3387 if (persist_data == NULL) {
3388 return -1;
3389 }
3390 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3391 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3392 /* We found it! */
3393 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3394 return 0;
3395 }
3396 }
3397
3398 return -1;
3399}
3400
Rubin Xu85c01f92014-10-13 12:49:54 +01003401static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003402{
3403 unsigned int i;
3404 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003405 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003406
3407 if (persist_data == NULL) {
3408 return -1;
3409 }
3410
Rubin Xu85c01f92014-10-13 12:49:54 +01003411 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003412
3413 num = persist_data->persist_valid_entries;
3414
3415 for (i = 0; i < num; i++) {
3416 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3417 /* We found an existing entry, update it! */
3418 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3419 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3420 return 0;
3421 }
3422 }
3423
3424 /* We didn't find it, add it to the end, if there is room */
3425 if (persist_data->persist_valid_entries < max_persistent_entries) {
3426 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3427 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3428 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3429 persist_data->persist_valid_entries++;
3430 return 0;
3431 }
3432
3433 return -1;
3434}
3435
Rubin Xu85c01f92014-10-13 12:49:54 +01003436/**
3437 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3438 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3439 */
3440static int match_multi_entry(const char *key, const char *field, unsigned index) {
3441 unsigned int i;
3442 unsigned int field_len;
3443 unsigned int key_index;
3444 field_len = strlen(field);
3445
3446 if (index == 0) {
3447 // The first key in a multi-entry field is just the filedname itself.
3448 if (!strcmp(key, field)) {
3449 return 1;
3450 }
3451 }
3452 // Match key against "%s_%d" % (field, index)
3453 if (strlen(key) < field_len + 1 + 1) {
3454 // Need at least a '_' and a digit.
3455 return 0;
3456 }
3457 if (strncmp(key, field, field_len)) {
3458 // If the key does not begin with field, it's not a match.
3459 return 0;
3460 }
3461 if (1 != sscanf(&key[field_len],"_%d", &key_index)) {
3462 return 0;
3463 }
3464 return key_index >= index;
3465}
3466
3467/*
3468 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3469 * remaining entries starting from index will be deleted.
3470 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3471 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3472 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3473 *
3474 */
3475static int persist_del_keys(const char *fieldname, unsigned index)
3476{
3477 unsigned int i;
3478 unsigned int j;
3479 unsigned int num;
3480
3481 if (persist_data == NULL) {
3482 return PERSIST_DEL_KEY_ERROR_OTHER;
3483 }
3484
3485 num = persist_data->persist_valid_entries;
3486
3487 j = 0; // points to the end of non-deleted entries.
3488 // Filter out to-be-deleted entries in place.
3489 for (i = 0; i < num; i++) {
3490 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3491 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3492 j++;
3493 }
3494 }
3495
3496 if (j < num) {
3497 persist_data->persist_valid_entries = j;
3498 // Zeroise the remaining entries
3499 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3500 return PERSIST_DEL_KEY_OK;
3501 } else {
3502 // Did not find an entry matching the given fieldname
3503 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3504 }
3505}
3506
3507static int persist_count_keys(const char *fieldname)
3508{
3509 unsigned int i;
3510 unsigned int count;
3511
3512 if (persist_data == NULL) {
3513 return -1;
3514 }
3515
3516 count = 0;
3517 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3518 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3519 count++;
3520 }
3521 }
3522
3523 return count;
3524}
3525
Ken Sumrall160b4d62013-04-22 12:15:39 -07003526/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003527int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003528{
3529 char temp_value[PROPERTY_VALUE_MAX];
3530 char real_blkdev[MAXPATHLEN];
Rubin Xu85c01f92014-10-13 12:49:54 +01003531 /* CRYPTO_GETFIELD_OK is success,
3532 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3533 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3534 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003535 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003536 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3537 int i;
3538 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003539
3540 if (persist_data == NULL) {
3541 load_persistent_data();
3542 if (persist_data == NULL) {
3543 SLOGE("Getfield error, cannot load persistent data");
3544 goto out;
3545 }
3546 }
3547
Rubin Xu85c01f92014-10-13 12:49:54 +01003548 // Read value from persistent entries. If the original value is split into multiple entries,
3549 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003550 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003551 // We found it, copy it to the caller's buffer and keep going until all entries are read.
3552 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
3553 // value too small
3554 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3555 goto out;
3556 }
3557 rc = CRYPTO_GETFIELD_OK;
3558
3559 for (i = 1; /* break explicitly */; i++) {
3560 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
3561 (int) sizeof(temp_field)) {
3562 // If the fieldname is very long, we stop as soon as it begins to overflow the
3563 // maximum field length. At this point we have in fact fully read out the original
3564 // value because cryptfs_setfield would not allow fields with longer names to be
3565 // written in the first place.
3566 break;
3567 }
3568 if (!persist_get_key(temp_field, temp_value)) {
3569 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3570 // value too small.
3571 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3572 goto out;
3573 }
3574 } else {
3575 // Exhaust all entries.
3576 break;
3577 }
3578 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003579 } else {
3580 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003581 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003582 }
3583
3584out:
3585 return rc;
3586}
3587
3588/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003589int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003590{
3591 struct crypt_persist_data stored_pdata;
3592 struct crypt_persist_data *pdata_p;
3593 struct crypt_mnt_ftr crypt_ftr;
3594 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003595 /* 0 is success, negative values are error */
3596 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003597 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003598 unsigned int field_id;
3599 char temp_field[PROPERTY_KEY_MAX];
3600 unsigned int num_entries;
3601 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003602
3603 if (persist_data == NULL) {
3604 load_persistent_data();
3605 if (persist_data == NULL) {
3606 SLOGE("Setfield error, cannot load persistent data");
3607 goto out;
3608 }
3609 }
3610
3611 property_get("ro.crypto.state", encrypted_state, "");
3612 if (!strcmp(encrypted_state, "encrypted") ) {
3613 encrypted = 1;
3614 }
3615
Rubin Xu85c01f92014-10-13 12:49:54 +01003616 // Compute the number of entries required to store value, each entry can store up to
3617 // (PROPERTY_VALUE_MAX - 1) chars
3618 if (strlen(value) == 0) {
3619 // Empty value also needs one entry to store.
3620 num_entries = 1;
3621 } else {
3622 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3623 }
3624
3625 max_keylen = strlen(fieldname);
3626 if (num_entries > 1) {
3627 // Need an extra "_%d" suffix.
3628 max_keylen += 1 + log10(num_entries);
3629 }
3630 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3631 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003632 goto out;
3633 }
3634
Rubin Xu85c01f92014-10-13 12:49:54 +01003635 // Make sure we have enough space to write the new value
3636 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3637 persist_get_max_entries(encrypted)) {
3638 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3639 goto out;
3640 }
3641
3642 // Now that we know persist_data has enough space for value, let's delete the old field first
3643 // to make up space.
3644 persist_del_keys(fieldname, 0);
3645
3646 if (persist_set_key(fieldname, value, encrypted)) {
3647 // fail to set key, should not happen as we have already checked the available space
3648 SLOGE("persist_set_key() error during setfield()");
3649 goto out;
3650 }
3651
3652 for (field_id = 1; field_id < num_entries; field_id++) {
3653 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
3654
3655 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3656 // fail to set key, should not happen as we have already checked the available space.
3657 SLOGE("persist_set_key() error during setfield()");
3658 goto out;
3659 }
3660 }
3661
Ken Sumrall160b4d62013-04-22 12:15:39 -07003662 /* If we are running encrypted, save the persistent data now */
3663 if (encrypted) {
3664 if (save_persistent_data()) {
3665 SLOGE("Setfield error, cannot save persistent data");
3666 goto out;
3667 }
3668 }
3669
Rubin Xu85c01f92014-10-13 12:49:54 +01003670 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003671
3672out:
3673 return rc;
3674}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003675
3676/* Checks userdata. Attempt to mount the volume if default-
3677 * encrypted.
3678 * On success trigger next init phase and return 0.
3679 * Currently do not handle failure - see TODO below.
3680 */
3681int cryptfs_mount_default_encrypted(void)
3682{
3683 char decrypt_state[PROPERTY_VALUE_MAX];
3684 property_get("vold.decrypt", decrypt_state, "0");
3685 if (!strcmp(decrypt_state, "0")) {
3686 SLOGE("Not encrypted - should not call here");
3687 } else {
3688 int crypt_type = cryptfs_get_password_type();
3689 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3690 SLOGE("Bad crypt type - error");
3691 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3692 SLOGD("Password is not default - "
3693 "starting min framework to prompt");
3694 property_set("vold.decrypt", "trigger_restart_min_framework");
3695 return 0;
3696 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3697 SLOGD("Password is default - restarting filesystem");
3698 cryptfs_restart_internal(0);
3699 return 0;
3700 } else {
3701 SLOGE("Encrypted, default crypt type but can't decrypt");
3702 }
3703 }
3704
Paul Lawrence6bfed202014-07-28 12:47:22 -07003705 /** Corrupt. Allow us to boot into framework, which will detect bad
3706 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003707 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003708 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003709 return 0;
3710}
3711
3712/* Returns type of the password, default, pattern, pin or password.
3713 */
3714int cryptfs_get_password_type(void)
3715{
3716 struct crypt_mnt_ftr crypt_ftr;
3717
3718 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3719 SLOGE("Error getting crypt footer and key\n");
3720 return -1;
3721 }
3722
Paul Lawrence6bfed202014-07-28 12:47:22 -07003723 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3724 return -1;
3725 }
3726
Paul Lawrencef4faa572014-01-29 13:31:03 -08003727 return crypt_ftr.crypt_type;
3728}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003729
Paul Lawrence399317e2014-03-10 13:20:50 -07003730char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003731{
Paul Lawrence399317e2014-03-10 13:20:50 -07003732 struct timespec now;
3733 clock_gettime(CLOCK_MONOTONIC, &now);
3734 if (now.tv_sec < password_expiry_time) {
3735 return password;
3736 } else {
3737 cryptfs_clear_password();
3738 return 0;
3739 }
3740}
3741
3742void cryptfs_clear_password()
3743{
3744 if (password) {
3745 size_t len = strlen(password);
3746 memset(password, 0, len);
3747 free(password);
3748 password = 0;
3749 password_expiry_time = 0;
3750 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003751}